2 // Copyright (c) 2002-2011 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
7 #include "compiler/OutputHLSL.h"
9 #include "compiler/debug.h"
10 #include "compiler/InfoSink.h"
11 #include "compiler/UnfoldSelect.h"
12 #include "compiler/SearchSymbol.h"
19 // Integer to TString conversion
23 sprintf(buffer, "%d", i);
27 OutputHLSL::OutputHLSL(TParseContext &context) : TIntermTraverser(true, true, true), mContext(context)
29 mUnfoldSelect = new UnfoldSelect(context, this);
30 mInsideFunction = false;
32 mUsesTexture2D = false;
33 mUsesTexture2D_bias = false;
34 mUsesTexture2DProj = false;
35 mUsesTexture2DProj_bias = false;
36 mUsesTexture2DProjLod = false;
37 mUsesTexture2DLod = false;
38 mUsesTextureCube = false;
39 mUsesTextureCube_bias = false;
40 mUsesTextureCubeLod = false;
41 mUsesDepthRange = false;
42 mUsesFragCoord = false;
43 mUsesPointCoord = false;
44 mUsesFrontFacing = false;
45 mUsesPointSize = false;
51 mUsesFaceforward1 = false;
52 mUsesFaceforward2 = false;
53 mUsesFaceforward3 = false;
54 mUsesFaceforward4 = false;
55 mUsesEqualMat2 = false;
56 mUsesEqualMat3 = false;
57 mUsesEqualMat4 = false;
58 mUsesEqualVec2 = false;
59 mUsesEqualVec3 = false;
60 mUsesEqualVec4 = false;
61 mUsesEqualIVec2 = false;
62 mUsesEqualIVec3 = false;
63 mUsesEqualIVec4 = false;
64 mUsesEqualBVec2 = false;
65 mUsesEqualBVec3 = false;
66 mUsesEqualBVec4 = false;
74 OutputHLSL::~OutputHLSL()
79 void OutputHLSL::output()
81 mContext.treeRoot->traverse(this); // Output the body first to determine what has to go in the header
84 mContext.infoSink.obj << mHeader.c_str();
85 mContext.infoSink.obj << mBody.c_str();
88 TInfoSinkBase &OutputHLSL::getBodyStream()
93 int OutputHLSL::vectorSize(const TType &type) const
95 int elementSize = type.isMatrix() ? type.getNominalSize() : 1;
96 int arraySize = type.isArray() ? type.getArraySize() : 1;
98 return elementSize * arraySize;
101 void OutputHLSL::header()
103 ShShaderType shaderType = mContext.shaderType;
104 TInfoSinkBase &out = mHeader;
106 for (StructDeclarations::iterator structDeclaration = mStructDeclarations.begin(); structDeclaration != mStructDeclarations.end(); structDeclaration++)
108 out << *structDeclaration;
111 for (Constructors::iterator constructor = mConstructors.begin(); constructor != mConstructors.end(); constructor++)
116 if (shaderType == SH_FRAGMENT_SHADER)
121 TSymbolTableLevel *symbols = mContext.symbolTable.getGlobalLevel();
122 int semanticIndex = 0;
124 for (TSymbolTableLevel::const_iterator namedSymbol = symbols->begin(); namedSymbol != symbols->end(); namedSymbol++)
126 const TSymbol *symbol = (*namedSymbol).second;
127 const TString &name = symbol->getName();
129 if (symbol->isVariable())
131 const TVariable *variable = static_cast<const TVariable*>(symbol);
132 const TType &type = variable->getType();
133 TQualifier qualifier = type.getQualifier();
135 if (qualifier == EvqUniform)
137 if (mReferencedUniforms.find(name.c_str()) != mReferencedUniforms.end())
139 uniforms += "uniform " + typeString(type) + " " + decorate(name) + arrayString(type) + ";\n";
142 else if (qualifier == EvqVaryingIn || qualifier == EvqInvariantVaryingIn)
144 if (mReferencedVaryings.find(name.c_str()) != mReferencedVaryings.end())
146 // Program linking depends on this exact format
147 varyings += "static " + typeString(type) + " " + decorate(name) + arrayString(type) + " = " + initializer(type) + ";\n";
149 semanticIndex += type.isArray() ? type.getArraySize() : 1;
152 else if (qualifier == EvqGlobal || qualifier == EvqTemporary)
154 // Globals are declared and intialized as an aggregate node
156 else if (qualifier == EvqConst)
158 // Constants are repeated as literals where used
164 out << "// Varyings\n";
167 "static float4 gl_Color[1] = {float4(0, 0, 0, 0)};\n";
171 out << "static float4 gl_FragCoord = float4(0, 0, 0, 0);\n";
176 out << "static float2 gl_PointCoord = float2(0.5, 0.5);\n";
179 if (mUsesFrontFacing)
181 out << "static bool gl_FrontFacing = false;\n";
188 out << "uniform float4 dx_Viewport;\n"
189 "uniform float2 dx_Depth;\n";
192 if (mUsesFrontFacing)
194 out << "uniform bool dx_PointsOrLines;\n"
195 "uniform bool dx_FrontCCW;\n";
202 // The texture fetch functions "flip" the Y coordinate in one way or another. This is because textures are stored
203 // according to the OpenGL convention, i.e. (0, 0) is "bottom left", rather than the D3D convention where (0, 0)
204 // is "top left". Since the HLSL texture fetch functions expect textures to be stored according to the D3D
205 // convention, the Y coordinate passed to these functions is adjusted to compensate.
207 // The simplest case is texture2D where the mapping is Y -> 1-Y, which maps [0, 1] -> [1, 0].
209 // The texture2DProj functions are more complicated because the projection divides by either Z or W. For the vec3
210 // case, the mapping is Y -> Z-Y or Y/Z -> 1-Y/Z, which again maps [0, 1] -> [1, 0].
212 // For cube textures the mapping is Y -> -Y, which maps [-1, 1] -> [1, -1]. This is not sufficient on its own for the
213 // +Y and -Y faces, which are now on the "wrong sides" of the cube. This is compensated for by exchanging the
214 // +Y and -Y faces everywhere else throughout the code.
218 out << "float4 gl_texture2D(sampler2D s, float2 t)\n"
220 " return tex2D(s, float2(t.x, 1 - t.y));\n"
225 if (mUsesTexture2D_bias)
227 out << "float4 gl_texture2D(sampler2D s, float2 t, float bias)\n"
229 " return tex2Dbias(s, float4(t.x, 1 - t.y, 0, bias));\n"
234 if (mUsesTexture2DProj)
236 out << "float4 gl_texture2DProj(sampler2D s, float3 t)\n"
238 " return tex2Dproj(s, float4(t.x, t.z - t.y, 0, t.z));\n"
241 "float4 gl_texture2DProj(sampler2D s, float4 t)\n"
243 " return tex2Dproj(s, float4(t.x, t.w - t.y, t.z, t.w));\n"
248 if (mUsesTexture2DProj_bias)
250 out << "float4 gl_texture2DProj(sampler2D s, float3 t, float bias)\n"
252 " return tex2Dbias(s, float4(t.x / t.z, 1 - (t.y / t.z), 0, bias));\n"
255 "float4 gl_texture2DProj(sampler2D s, float4 t, float bias)\n"
257 " return tex2Dbias(s, float4(t.x / t.w, 1 - (t.y / t.w), 0, bias));\n"
262 if (mUsesTextureCube)
264 out << "float4 gl_textureCube(samplerCUBE s, float3 t)\n"
266 " return texCUBE(s, float3(t.x, -t.y, t.z));\n"
271 if (mUsesTextureCube_bias)
273 out << "float4 gl_textureCube(samplerCUBE s, float3 t, float bias)\n"
275 " return texCUBEbias(s, float4(t.x, -t.y, t.z, bias));\n"
280 else // Vertex shader
286 TSymbolTableLevel *symbols = mContext.symbolTable.getGlobalLevel();
288 for (TSymbolTableLevel::const_iterator namedSymbol = symbols->begin(); namedSymbol != symbols->end(); namedSymbol++)
290 const TSymbol *symbol = (*namedSymbol).second;
291 const TString &name = symbol->getName();
293 if (symbol->isVariable())
295 const TVariable *variable = static_cast<const TVariable*>(symbol);
296 const TType &type = variable->getType();
297 TQualifier qualifier = type.getQualifier();
299 if (qualifier == EvqUniform)
301 if (mReferencedUniforms.find(name.c_str()) != mReferencedUniforms.end())
303 uniforms += "uniform " + typeString(type) + " " + decorate(name) + arrayString(type) + ";\n";
306 else if (qualifier == EvqAttribute)
308 if (mReferencedAttributes.find(name.c_str()) != mReferencedAttributes.end())
310 attributes += "static " + typeString(type) + " " + decorate(name) + arrayString(type) + " = " + initializer(type) + ";\n";
313 else if (qualifier == EvqVaryingOut || qualifier == EvqInvariantVaryingOut)
315 if (mReferencedVaryings.find(name.c_str()) != mReferencedVaryings.end())
317 // Program linking depends on this exact format
318 varyings += "static " + typeString(type) + " " + decorate(name) + arrayString(type) + " = " + initializer(type) + ";\n";
321 else if (qualifier == EvqGlobal || qualifier == EvqTemporary)
323 // Globals are declared and intialized as an aggregate node
325 else if (qualifier == EvqConst)
327 // Constants are repeated as literals where used
333 out << "// Attributes\n";
336 "static float4 gl_Position = float4(0, 0, 0, 0);\n";
340 out << "static float gl_PointSize = float(1);\n";
347 "uniform float2 dx_HalfPixelSize;\n"
352 // The texture fetch functions "flip" the Y coordinate in one way or another. This is because textures are stored
353 // according to the OpenGL convention, i.e. (0, 0) is "bottom left", rather than the D3D convention where (0, 0)
354 // is "top left". Since the HLSL texture fetch functions expect textures to be stored according to the D3D
355 // convention, the Y coordinate passed to these functions is adjusted to compensate.
357 // The simplest case is texture2D where the mapping is Y -> 1-Y, which maps [0, 1] -> [1, 0].
359 // The texture2DProj functions are more complicated because the projection divides by either Z or W. For the vec3
360 // case, the mapping is Y -> Z-Y or Y/Z -> 1-Y/Z, which again maps [0, 1] -> [1, 0].
362 // For cube textures the mapping is Y -> -Y, which maps [-1, 1] -> [1, -1]. This is not sufficient on its own for the
363 // +Y and -Y faces, which are now on the "wrong sides" of the cube. This is compensated for by exchanging the
364 // +Y and -Y faces everywhere else throughout the code.
368 out << "float4 gl_texture2D(sampler2D s, float2 t)\n"
370 " return tex2Dlod(s, float4(t.x, 1 - t.y, 0, 0));\n"
375 if (mUsesTexture2DLod)
377 out << "float4 gl_texture2DLod(sampler2D s, float2 t, float lod)\n"
379 " return tex2Dlod(s, float4(t.x, 1 - t.y, 0, lod));\n"
384 if (mUsesTexture2DProj)
386 out << "float4 gl_texture2DProj(sampler2D s, float3 t)\n"
388 " return tex2Dlod(s, float4(t.x / t.z, 1 - t.y / t.z, 0, 0));\n"
391 "float4 gl_texture2DProj(sampler2D s, float4 t)\n"
393 " return tex2Dlod(s, float4(t.x / t.w, 1 - t.y / t.w, 0, 0));\n"
398 if (mUsesTexture2DProjLod)
400 out << "float4 gl_texture2DProjLod(sampler2D s, float3 t, float lod)\n"
402 " return tex2Dlod(s, float4(t.x / t.z, 1 - t.y / t.z, 0, lod));\n"
405 "float4 gl_texture2DProjLod(sampler2D s, float4 t, float lod)\n"
407 " return tex2Dlod(s, float4(t.x / t.w, 1 - t.y / t.w, 0, lod));\n"
412 if (mUsesTextureCube)
414 out << "float4 gl_textureCube(samplerCUBE s, float3 t)\n"
416 " return texCUBElod(s, float4(t.x, -t.y, t.z, 0));\n"
421 if (mUsesTextureCubeLod)
423 out << "float4 gl_textureCubeLod(samplerCUBE s, float3 t, float lod)\n"
425 " return texCUBElod(s, float4(t.x, -t.y, t.z, lod));\n"
433 out << "#define GL_USES_FRAG_COORD\n";
438 out << "#define GL_USES_POINT_COORD\n";
441 if (mUsesFrontFacing)
443 out << "#define GL_USES_FRONT_FACING\n";
448 out << "#define GL_USES_POINT_SIZE\n";
453 out << "struct gl_DepthRangeParameters\n"
460 "uniform float3 dx_DepthRange;"
461 "static gl_DepthRangeParameters gl_DepthRange = {dx_DepthRange.x, dx_DepthRange.y, dx_DepthRange.z};\n"
467 out << "bool xor(bool p, bool q)\n"
469 " return (p || q) && !(p && q);\n"
476 out << "float mod(float x, float y)\n"
478 " return x - y * floor(x / y);\n"
485 out << "float2 mod(float2 x, float y)\n"
487 " return x - y * floor(x / y);\n"
494 out << "float3 mod(float3 x, float y)\n"
496 " return x - y * floor(x / y);\n"
503 out << "float4 mod(float4 x, float y)\n"
505 " return x - y * floor(x / y);\n"
510 if (mUsesFaceforward1)
512 out << "float faceforward(float N, float I, float Nref)\n"
514 " if(dot(Nref, I) >= 0)\n"
526 if (mUsesFaceforward2)
528 out << "float2 faceforward(float2 N, float2 I, float2 Nref)\n"
530 " if(dot(Nref, I) >= 0)\n"
542 if (mUsesFaceforward3)
544 out << "float3 faceforward(float3 N, float3 I, float3 Nref)\n"
546 " if(dot(Nref, I) >= 0)\n"
558 if (mUsesFaceforward4)
560 out << "float4 faceforward(float4 N, float4 I, float4 Nref)\n"
562 " if(dot(Nref, I) >= 0)\n"
576 out << "bool equal(float2x2 m, float2x2 n)\n"
578 " return m[0][0] == n[0][0] && m[0][1] == n[0][1] &&\n"
579 " m[1][0] == n[1][0] && m[1][1] == n[1][1];\n"
585 out << "bool equal(float3x3 m, float3x3 n)\n"
587 " return m[0][0] == n[0][0] && m[0][1] == n[0][1] && m[0][2] == n[0][2] &&\n"
588 " m[1][0] == n[1][0] && m[1][1] == n[1][1] && m[1][2] == n[1][2] &&\n"
589 " m[2][0] == n[2][0] && m[2][1] == n[2][1] && m[2][2] == n[2][2];\n"
595 out << "bool equal(float4x4 m, float4x4 n)\n"
597 " return m[0][0] == n[0][0] && m[0][1] == n[0][1] && m[0][2] == n[0][2] && m[0][3] == n[0][3] &&\n"
598 " m[1][0] == n[1][0] && m[1][1] == n[1][1] && m[1][2] == n[1][2] && m[1][3] == n[1][3] &&\n"
599 " m[2][0] == n[2][0] && m[2][1] == n[2][1] && m[2][2] == n[2][2] && m[2][3] == n[2][3] &&\n"
600 " m[3][0] == n[3][0] && m[3][1] == n[3][1] && m[3][2] == n[3][2] && m[3][3] == n[3][3];\n"
606 out << "bool equal(float2 v, float2 u)\n"
608 " return v.x == u.x && v.y == u.y;\n"
614 out << "bool equal(float3 v, float3 u)\n"
616 " return v.x == u.x && v.y == u.y && v.z == u.z;\n"
622 out << "bool equal(float4 v, float4 u)\n"
624 " return v.x == u.x && v.y == u.y && v.z == u.z && v.w == u.w;\n"
630 out << "bool equal(int2 v, int2 u)\n"
632 " return v.x == u.x && v.y == u.y;\n"
638 out << "bool equal(int3 v, int3 u)\n"
640 " return v.x == u.x && v.y == u.y && v.z == u.z;\n"
646 out << "bool equal(int4 v, int4 u)\n"
648 " return v.x == u.x && v.y == u.y && v.z == u.z && v.w == u.w;\n"
654 out << "bool equal(bool2 v, bool2 u)\n"
656 " return v.x == u.x && v.y == u.y;\n"
662 out << "bool equal(bool3 v, bool3 u)\n"
664 " return v.x == u.x && v.y == u.y && v.z == u.z;\n"
670 out << "bool equal(bool4 v, bool4 u)\n"
672 " return v.x == u.x && v.y == u.y && v.z == u.z && v.w == u.w;\n"
678 out << "float atanyx(float y, float x)\n"
680 " if(x == 0 && y == 0) x = 1;\n" // Avoid producing a NaN
681 " return atan2(y, x);\n"
686 void OutputHLSL::visitSymbol(TIntermSymbol *node)
688 TInfoSinkBase &out = mBody;
690 TString name = node->getSymbol();
692 if (name == "gl_FragColor")
694 out << "gl_Color[0]";
696 else if (name == "gl_FragData")
700 else if (name == "gl_DepthRange")
702 mUsesDepthRange = true;
705 else if (name == "gl_FragCoord")
707 mUsesFragCoord = true;
710 else if (name == "gl_PointCoord")
712 mUsesPointCoord = true;
715 else if (name == "gl_FrontFacing")
717 mUsesFrontFacing = true;
720 else if (name == "gl_PointSize")
722 mUsesPointSize = true;
727 TQualifier qualifier = node->getQualifier();
729 if (qualifier == EvqUniform)
731 mReferencedUniforms.insert(name.c_str());
733 else if (qualifier == EvqAttribute)
735 mReferencedAttributes.insert(name.c_str());
737 else if (qualifier == EvqVaryingOut || qualifier == EvqInvariantVaryingOut || qualifier == EvqVaryingIn || qualifier == EvqInvariantVaryingIn)
739 mReferencedVaryings.insert(name.c_str());
742 out << decorate(name);
746 bool OutputHLSL::visitBinary(Visit visit, TIntermBinary *node)
748 TInfoSinkBase &out = mBody;
750 switch (node->getOp())
752 case EOpAssign: outputTriplet(visit, "(", " = ", ")"); break;
754 if (visit == PreVisit)
756 // GLSL allows to write things like "float x = x;" where a new variable x is defined
757 // and the value of an existing variable x is assigned. HLSL uses C semantics (the
758 // new variable is created before the assignment is evaluated), so we need to convert
759 // this to "float t = x, x = t;".
761 TIntermSymbol *symbolNode = node->getLeft()->getAsSymbolNode();
762 TIntermTyped *expression = node->getRight();
764 sh::SearchSymbol searchSymbol(symbolNode->getSymbol());
765 expression->traverse(&searchSymbol);
766 bool sameSymbol = searchSymbol.foundMatch();
770 // Type already printed
771 out << "t" + str(mUniqueIndex) + " = ";
772 expression->traverse(this);
774 symbolNode->traverse(this);
775 out << " = t" + str(mUniqueIndex);
781 else if (visit == InVisit)
786 case EOpAddAssign: outputTriplet(visit, "(", " += ", ")"); break;
787 case EOpSubAssign: outputTriplet(visit, "(", " -= ", ")"); break;
788 case EOpMulAssign: outputTriplet(visit, "(", " *= ", ")"); break;
789 case EOpVectorTimesScalarAssign: outputTriplet(visit, "(", " *= ", ")"); break;
790 case EOpMatrixTimesScalarAssign: outputTriplet(visit, "(", " *= ", ")"); break;
791 case EOpVectorTimesMatrixAssign:
792 if (visit == PreVisit)
796 else if (visit == InVisit)
799 node->getLeft()->traverse(this);
800 out << ", transpose(";
807 case EOpMatrixTimesMatrixAssign:
808 if (visit == PreVisit)
812 else if (visit == InVisit)
815 node->getLeft()->traverse(this);
823 case EOpDivAssign: outputTriplet(visit, "(", " /= ", ")"); break;
824 case EOpIndexDirect: outputTriplet(visit, "", "[", "]"); break;
825 case EOpIndexIndirect: outputTriplet(visit, "", "[", "]"); break;
826 case EOpIndexDirectStruct:
827 if (visit == InVisit)
829 out << "." + node->getType().getFieldName();
834 case EOpVectorSwizzle:
835 if (visit == InVisit)
839 TIntermAggregate *swizzle = node->getRight()->getAsAggregate();
843 TIntermSequence &sequence = swizzle->getSequence();
845 for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
847 TIntermConstantUnion *element = (*sit)->getAsConstantUnion();
851 int i = element->getUnionArrayPointer()[0].getIConst();
855 case 0: out << "x"; break;
856 case 1: out << "y"; break;
857 case 2: out << "z"; break;
858 case 3: out << "w"; break;
859 default: UNREACHABLE();
867 return false; // Fully processed
870 case EOpAdd: outputTriplet(visit, "(", " + ", ")"); break;
871 case EOpSub: outputTriplet(visit, "(", " - ", ")"); break;
872 case EOpMul: outputTriplet(visit, "(", " * ", ")"); break;
873 case EOpDiv: outputTriplet(visit, "(", " / ", ")"); break;
876 if (node->getLeft()->isScalar())
878 if (node->getOp() == EOpEqual)
880 outputTriplet(visit, "(", " == ", ")");
884 outputTriplet(visit, "(", " != ", ")");
887 else if (node->getLeft()->getBasicType() == EbtStruct)
889 if (node->getOp() == EOpEqual)
898 const TTypeList *fields = node->getLeft()->getType().getStruct();
900 for (size_t i = 0; i < fields->size(); i++)
902 const TType *fieldType = (*fields)[i].type;
904 node->getLeft()->traverse(this);
905 out << "." + fieldType->getFieldName() + " == ";
906 node->getRight()->traverse(this);
907 out << "." + fieldType->getFieldName();
909 if (i < fields->size() - 1)
921 if (node->getLeft()->isMatrix())
923 switch (node->getLeft()->getNominalSize())
925 case 2: mUsesEqualMat2 = true; break;
926 case 3: mUsesEqualMat3 = true; break;
927 case 4: mUsesEqualMat4 = true; break;
928 default: UNREACHABLE();
931 else if (node->getLeft()->isVector())
933 switch (node->getLeft()->getBasicType())
936 switch (node->getLeft()->getNominalSize())
938 case 2: mUsesEqualVec2 = true; break;
939 case 3: mUsesEqualVec3 = true; break;
940 case 4: mUsesEqualVec4 = true; break;
941 default: UNREACHABLE();
945 switch (node->getLeft()->getNominalSize())
947 case 2: mUsesEqualIVec2 = true; break;
948 case 3: mUsesEqualIVec3 = true; break;
949 case 4: mUsesEqualIVec4 = true; break;
950 default: UNREACHABLE();
954 switch (node->getLeft()->getNominalSize())
956 case 2: mUsesEqualBVec2 = true; break;
957 case 3: mUsesEqualBVec3 = true; break;
958 case 4: mUsesEqualBVec4 = true; break;
959 default: UNREACHABLE();
962 default: UNREACHABLE();
967 if (node->getOp() == EOpEqual)
969 outputTriplet(visit, "equal(", ", ", ")");
973 outputTriplet(visit, "!equal(", ", ", ")");
977 case EOpLessThan: outputTriplet(visit, "(", " < ", ")"); break;
978 case EOpGreaterThan: outputTriplet(visit, "(", " > ", ")"); break;
979 case EOpLessThanEqual: outputTriplet(visit, "(", " <= ", ")"); break;
980 case EOpGreaterThanEqual: outputTriplet(visit, "(", " >= ", ")"); break;
981 case EOpVectorTimesScalar: outputTriplet(visit, "(", " * ", ")"); break;
982 case EOpMatrixTimesScalar: outputTriplet(visit, "(", " * ", ")"); break;
983 case EOpVectorTimesMatrix: outputTriplet(visit, "mul(", ", transpose(", "))"); break;
984 case EOpMatrixTimesVector: outputTriplet(visit, "mul(transpose(", "), ", ")"); break;
985 case EOpMatrixTimesMatrix: outputTriplet(visit, "transpose(mul(transpose(", "), transpose(", ")))"); break;
986 case EOpLogicalOr: outputTriplet(visit, "(", " || ", ")"); break;
989 outputTriplet(visit, "xor(", ", ", ")");
991 case EOpLogicalAnd: outputTriplet(visit, "(", " && ", ")"); break;
992 default: UNREACHABLE();
998 bool OutputHLSL::visitUnary(Visit visit, TIntermUnary *node)
1000 TInfoSinkBase &out = mBody;
1002 switch (node->getOp())
1004 case EOpNegative: outputTriplet(visit, "(-", "", ")"); break;
1005 case EOpVectorLogicalNot: outputTriplet(visit, "(!", "", ")"); break;
1006 case EOpLogicalNot: outputTriplet(visit, "(!", "", ")"); break;
1007 case EOpPostIncrement: outputTriplet(visit, "(", "", "++)"); break;
1008 case EOpPostDecrement: outputTriplet(visit, "(", "", "--)"); break;
1009 case EOpPreIncrement: outputTriplet(visit, "(++", "", ")"); break;
1010 case EOpPreDecrement: outputTriplet(visit, "(--", "", ")"); break;
1011 case EOpConvIntToBool:
1012 case EOpConvFloatToBool:
1013 switch (node->getOperand()->getType().getNominalSize())
1015 case 1: outputTriplet(visit, "bool(", "", ")"); break;
1016 case 2: outputTriplet(visit, "bool2(", "", ")"); break;
1017 case 3: outputTriplet(visit, "bool3(", "", ")"); break;
1018 case 4: outputTriplet(visit, "bool4(", "", ")"); break;
1019 default: UNREACHABLE();
1022 case EOpConvBoolToFloat:
1023 case EOpConvIntToFloat:
1024 switch (node->getOperand()->getType().getNominalSize())
1026 case 1: outputTriplet(visit, "float(", "", ")"); break;
1027 case 2: outputTriplet(visit, "float2(", "", ")"); break;
1028 case 3: outputTriplet(visit, "float3(", "", ")"); break;
1029 case 4: outputTriplet(visit, "float4(", "", ")"); break;
1030 default: UNREACHABLE();
1033 case EOpConvFloatToInt:
1034 case EOpConvBoolToInt:
1035 switch (node->getOperand()->getType().getNominalSize())
1037 case 1: outputTriplet(visit, "int(", "", ")"); break;
1038 case 2: outputTriplet(visit, "int2(", "", ")"); break;
1039 case 3: outputTriplet(visit, "int3(", "", ")"); break;
1040 case 4: outputTriplet(visit, "int4(", "", ")"); break;
1041 default: UNREACHABLE();
1044 case EOpRadians: outputTriplet(visit, "radians(", "", ")"); break;
1045 case EOpDegrees: outputTriplet(visit, "degrees(", "", ")"); break;
1046 case EOpSin: outputTriplet(visit, "sin(", "", ")"); break;
1047 case EOpCos: outputTriplet(visit, "cos(", "", ")"); break;
1048 case EOpTan: outputTriplet(visit, "tan(", "", ")"); break;
1049 case EOpAsin: outputTriplet(visit, "asin(", "", ")"); break;
1050 case EOpAcos: outputTriplet(visit, "acos(", "", ")"); break;
1051 case EOpAtan: outputTriplet(visit, "atan(", "", ")"); break;
1052 case EOpExp: outputTriplet(visit, "exp(", "", ")"); break;
1053 case EOpLog: outputTriplet(visit, "log(", "", ")"); break;
1054 case EOpExp2: outputTriplet(visit, "exp2(", "", ")"); break;
1055 case EOpLog2: outputTriplet(visit, "log2(", "", ")"); break;
1056 case EOpSqrt: outputTriplet(visit, "sqrt(", "", ")"); break;
1057 case EOpInverseSqrt: outputTriplet(visit, "rsqrt(", "", ")"); break;
1058 case EOpAbs: outputTriplet(visit, "abs(", "", ")"); break;
1059 case EOpSign: outputTriplet(visit, "sign(", "", ")"); break;
1060 case EOpFloor: outputTriplet(visit, "floor(", "", ")"); break;
1061 case EOpCeil: outputTriplet(visit, "ceil(", "", ")"); break;
1062 case EOpFract: outputTriplet(visit, "frac(", "", ")"); break;
1063 case EOpLength: outputTriplet(visit, "length(", "", ")"); break;
1064 case EOpNormalize: outputTriplet(visit, "normalize(", "", ")"); break;
1065 case EOpDFdx: outputTriplet(visit, "ddx(", "", ")"); break;
1066 case EOpDFdy: outputTriplet(visit, "(-ddy(", "", "))"); break;
1067 case EOpFwidth: outputTriplet(visit, "fwidth(", "", ")"); break;
1068 case EOpAny: outputTriplet(visit, "any(", "", ")"); break;
1069 case EOpAll: outputTriplet(visit, "all(", "", ")"); break;
1070 default: UNREACHABLE();
1076 bool OutputHLSL::visitAggregate(Visit visit, TIntermAggregate *node)
1078 ShShaderType shaderType = mContext.shaderType;
1079 TInfoSinkBase &out = mBody;
1081 switch (node->getOp())
1085 if (mInsideFunction)
1087 outputLineDirective(node->getLine());
1092 if (mScopeBracket.size() < mScopeDepth)
1094 mScopeBracket.push_back(0); // New scope level
1098 mScopeBracket[mScopeDepth - 1]++; // New scope at existing level
1102 for (TIntermSequence::iterator sit = node->getSequence().begin(); sit != node->getSequence().end(); sit++)
1104 outputLineDirective((*sit)->getLine());
1106 if (isSingleStatement(*sit))
1108 mUnfoldSelect->traverse(*sit);
1111 (*sit)->traverse(this);
1116 if (mInsideFunction)
1118 outputLineDirective(node->getEndLine());
1126 case EOpDeclaration:
1127 if (visit == PreVisit)
1129 TIntermSequence &sequence = node->getSequence();
1130 TIntermTyped *variable = sequence[0]->getAsTyped();
1133 if (variable && (variable->getQualifier() == EvqTemporary || variable->getQualifier() == EvqGlobal))
1135 if (variable->getType().getStruct())
1137 addConstructor(variable->getType(), scopedStruct(variable->getType().getTypeName()), NULL);
1140 if (!variable->getAsSymbolNode() || variable->getAsSymbolNode()->getSymbol() != "") // Variable declaration
1142 if (!mInsideFunction)
1147 out << typeString(variable->getType()) + " ";
1149 for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
1151 TIntermSymbol *symbol = (*sit)->getAsSymbolNode();
1155 symbol->traverse(this);
1156 out << arrayString(symbol->getType());
1157 out << " = " + initializer(variable->getType());
1161 (*sit)->traverse(this);
1164 if (visit && this->inVisit)
1166 if (*sit != sequence.back())
1168 visit = this->visitAggregate(InVisit, node);
1173 if (visit && this->postVisit)
1175 this->visitAggregate(PostVisit, node);
1178 else if (variable->getAsSymbolNode() && variable->getAsSymbolNode()->getSymbol() == "") // Type (struct) declaration
1180 // Already added to constructor map
1187 else if (visit == InVisit)
1193 if (visit == PreVisit)
1195 out << typeString(node->getType()) << " " << decorate(node->getName()) << "(";
1197 TIntermSequence &arguments = node->getSequence();
1199 for (unsigned int i = 0; i < arguments.size(); i++)
1201 TIntermSymbol *symbol = arguments[i]->getAsSymbolNode();
1205 out << argumentString(symbol);
1207 if (i < arguments.size() - 1)
1220 case EOpComma: outputTriplet(visit, "", ", ", ""); break;
1223 TString name = TFunction::unmangleName(node->getName());
1225 if (visit == PreVisit)
1227 out << typeString(node->getType()) << " ";
1235 out << decorate(name) << "(";
1238 TIntermSequence &sequence = node->getSequence();
1239 TIntermSequence &arguments = sequence[0]->getAsAggregate()->getSequence();
1241 for (unsigned int i = 0; i < arguments.size(); i++)
1243 TIntermSymbol *symbol = arguments[i]->getAsSymbolNode();
1247 out << argumentString(symbol);
1249 if (i < arguments.size() - 1)
1257 sequence.erase(sequence.begin());
1261 outputLineDirective(node->getLine());
1264 mInsideFunction = true;
1266 else if (visit == PostVisit)
1268 outputLineDirective(node->getEndLine());
1271 mInsideFunction = false;
1275 case EOpFunctionCall:
1277 if (visit == PreVisit)
1279 TString name = TFunction::unmangleName(node->getName());
1281 if (node->isUserDefined())
1283 out << decorate(name) << "(";
1287 if (name == "texture2D")
1289 if (node->getSequence().size() == 2)
1291 mUsesTexture2D = true;
1293 else if (node->getSequence().size() == 3)
1295 mUsesTexture2D_bias = true;
1299 out << "gl_texture2D(";
1301 else if (name == "texture2DProj")
1303 if (node->getSequence().size() == 2)
1305 mUsesTexture2DProj = true;
1307 else if (node->getSequence().size() == 3)
1309 mUsesTexture2DProj_bias = true;
1313 out << "gl_texture2DProj(";
1315 else if (name == "textureCube")
1317 if (node->getSequence().size() == 2)
1319 mUsesTextureCube = true;
1321 else if (node->getSequence().size() == 3)
1323 mUsesTextureCube_bias = true;
1327 out << "gl_textureCube(";
1329 else if (name == "texture2DLod")
1331 if (node->getSequence().size() == 3)
1333 mUsesTexture2DLod = true;
1337 out << "gl_texture2DLod(";
1339 else if (name == "texture2DProjLod")
1341 if (node->getSequence().size() == 3)
1343 mUsesTexture2DProjLod = true;
1347 out << "gl_texture2DProjLod(";
1349 else if (name == "textureCubeLod")
1351 if (node->getSequence().size() == 3)
1353 mUsesTextureCubeLod = true;
1357 out << "gl_textureCubeLod(";
1362 else if (visit == InVisit)
1372 case EOpParameters: outputTriplet(visit, "(", ", ", ")\n{\n"); break;
1373 case EOpConstructFloat:
1374 addConstructor(node->getType(), "vec1", &node->getSequence());
1375 outputTriplet(visit, "vec1(", "", ")");
1377 case EOpConstructVec2:
1378 addConstructor(node->getType(), "vec2", &node->getSequence());
1379 outputTriplet(visit, "vec2(", ", ", ")");
1381 case EOpConstructVec3:
1382 addConstructor(node->getType(), "vec3", &node->getSequence());
1383 outputTriplet(visit, "vec3(", ", ", ")");
1385 case EOpConstructVec4:
1386 addConstructor(node->getType(), "vec4", &node->getSequence());
1387 outputTriplet(visit, "vec4(", ", ", ")");
1389 case EOpConstructBool:
1390 addConstructor(node->getType(), "bvec1", &node->getSequence());
1391 outputTriplet(visit, "bvec1(", "", ")");
1393 case EOpConstructBVec2:
1394 addConstructor(node->getType(), "bvec2", &node->getSequence());
1395 outputTriplet(visit, "bvec2(", ", ", ")");
1397 case EOpConstructBVec3:
1398 addConstructor(node->getType(), "bvec3", &node->getSequence());
1399 outputTriplet(visit, "bvec3(", ", ", ")");
1401 case EOpConstructBVec4:
1402 addConstructor(node->getType(), "bvec4", &node->getSequence());
1403 outputTriplet(visit, "bvec4(", ", ", ")");
1405 case EOpConstructInt:
1406 addConstructor(node->getType(), "ivec1", &node->getSequence());
1407 outputTriplet(visit, "ivec1(", "", ")");
1409 case EOpConstructIVec2:
1410 addConstructor(node->getType(), "ivec2", &node->getSequence());
1411 outputTriplet(visit, "ivec2(", ", ", ")");
1413 case EOpConstructIVec3:
1414 addConstructor(node->getType(), "ivec3", &node->getSequence());
1415 outputTriplet(visit, "ivec3(", ", ", ")");
1417 case EOpConstructIVec4:
1418 addConstructor(node->getType(), "ivec4", &node->getSequence());
1419 outputTriplet(visit, "ivec4(", ", ", ")");
1421 case EOpConstructMat2:
1422 addConstructor(node->getType(), "mat2", &node->getSequence());
1423 outputTriplet(visit, "mat2(", ", ", ")");
1425 case EOpConstructMat3:
1426 addConstructor(node->getType(), "mat3", &node->getSequence());
1427 outputTriplet(visit, "mat3(", ", ", ")");
1429 case EOpConstructMat4:
1430 addConstructor(node->getType(), "mat4", &node->getSequence());
1431 outputTriplet(visit, "mat4(", ", ", ")");
1433 case EOpConstructStruct:
1434 addConstructor(node->getType(), scopedStruct(node->getType().getTypeName()), &node->getSequence());
1435 outputTriplet(visit, structLookup(node->getType().getTypeName()) + "_ctor(", ", ", ")");
1437 case EOpLessThan: outputTriplet(visit, "(", " < ", ")"); break;
1438 case EOpGreaterThan: outputTriplet(visit, "(", " > ", ")"); break;
1439 case EOpLessThanEqual: outputTriplet(visit, "(", " <= ", ")"); break;
1440 case EOpGreaterThanEqual: outputTriplet(visit, "(", " >= ", ")"); break;
1441 case EOpVectorEqual: outputTriplet(visit, "(", " == ", ")"); break;
1442 case EOpVectorNotEqual: outputTriplet(visit, "(", " != ", ")"); break;
1445 switch (node->getSequence()[0]->getAsTyped()->getNominalSize()) // Number of components in the first argument
1447 case 1: mUsesMod1 = true; break;
1448 case 2: mUsesMod2 = true; break;
1449 case 3: mUsesMod3 = true; break;
1450 case 4: mUsesMod4 = true; break;
1451 default: UNREACHABLE();
1454 outputTriplet(visit, "mod(", ", ", ")");
1457 case EOpPow: outputTriplet(visit, "pow(", ", ", ")"); break;
1459 ASSERT(node->getSequence().size() == 2); // atan(x) is a unary operator
1461 outputTriplet(visit, "atanyx(", ", ", ")");
1463 case EOpMin: outputTriplet(visit, "min(", ", ", ")"); break;
1464 case EOpMax: outputTriplet(visit, "max(", ", ", ")"); break;
1465 case EOpClamp: outputTriplet(visit, "clamp(", ", ", ")"); break;
1466 case EOpMix: outputTriplet(visit, "lerp(", ", ", ")"); break;
1467 case EOpStep: outputTriplet(visit, "step(", ", ", ")"); break;
1468 case EOpSmoothStep: outputTriplet(visit, "smoothstep(", ", ", ")"); break;
1469 case EOpDistance: outputTriplet(visit, "distance(", ", ", ")"); break;
1470 case EOpDot: outputTriplet(visit, "dot(", ", ", ")"); break;
1471 case EOpCross: outputTriplet(visit, "cross(", ", ", ")"); break;
1472 case EOpFaceForward:
1474 switch (node->getSequence()[0]->getAsTyped()->getNominalSize()) // Number of components in the first argument
1476 case 1: mUsesFaceforward1 = true; break;
1477 case 2: mUsesFaceforward2 = true; break;
1478 case 3: mUsesFaceforward3 = true; break;
1479 case 4: mUsesFaceforward4 = true; break;
1480 default: UNREACHABLE();
1483 outputTriplet(visit, "faceforward(", ", ", ")");
1486 case EOpReflect: outputTriplet(visit, "reflect(", ", ", ")"); break;
1487 case EOpRefract: outputTriplet(visit, "refract(", ", ", ")"); break;
1488 case EOpMul: outputTriplet(visit, "(", " * ", ")"); break;
1489 default: UNREACHABLE();
1495 bool OutputHLSL::visitSelection(Visit visit, TIntermSelection *node)
1497 TInfoSinkBase &out = mBody;
1499 if (node->usesTernaryOperator())
1501 out << "t" << mUnfoldSelect->getTemporaryIndex();
1503 else // if/else statement
1505 mUnfoldSelect->traverse(node->getCondition());
1509 node->getCondition()->traverse(this);
1513 outputLineDirective(node->getLine());
1516 if (node->getTrueBlock())
1518 node->getTrueBlock()->traverse(this);
1521 outputLineDirective(node->getLine());
1524 if (node->getFalseBlock())
1528 outputLineDirective(node->getFalseBlock()->getLine());
1531 outputLineDirective(node->getFalseBlock()->getLine());
1532 node->getFalseBlock()->traverse(this);
1534 outputLineDirective(node->getFalseBlock()->getLine());
1542 void OutputHLSL::visitConstantUnion(TIntermConstantUnion *node)
1544 writeConstantUnion(node->getType(), node->getUnionArrayPointer());
1547 bool OutputHLSL::visitLoop(Visit visit, TIntermLoop *node)
1549 if (handleExcessiveLoop(node))
1554 TInfoSinkBase &out = mBody;
1556 if (node->getType() == ELoopDoWhile)
1560 outputLineDirective(node->getLine());
1565 if (node->getInit())
1567 mUnfoldSelect->traverse(node->getInit());
1570 if (node->getCondition())
1572 mUnfoldSelect->traverse(node->getCondition());
1575 if (node->getExpression())
1577 mUnfoldSelect->traverse(node->getExpression());
1582 if (node->getInit())
1584 node->getInit()->traverse(this);
1589 if (node->getCondition())
1591 node->getCondition()->traverse(this);
1596 if (node->getExpression())
1598 node->getExpression()->traverse(this);
1603 outputLineDirective(node->getLine());
1607 if (node->getBody())
1609 node->getBody()->traverse(this);
1612 outputLineDirective(node->getLine());
1615 if (node->getType() == ELoopDoWhile)
1617 outputLineDirective(node->getCondition()->getLine());
1620 node->getCondition()->traverse(this);
1630 bool OutputHLSL::visitBranch(Visit visit, TIntermBranch *node)
1632 TInfoSinkBase &out = mBody;
1634 switch (node->getFlowOp())
1636 case EOpKill: outputTriplet(visit, "discard;\n", "", ""); break;
1637 case EOpBreak: outputTriplet(visit, "break;\n", "", ""); break;
1638 case EOpContinue: outputTriplet(visit, "continue;\n", "", ""); break;
1640 if (visit == PreVisit)
1642 if (node->getExpression())
1651 else if (visit == PostVisit)
1653 if (node->getExpression())
1659 default: UNREACHABLE();
1665 bool OutputHLSL::isSingleStatement(TIntermNode *node)
1667 TIntermAggregate *aggregate = node->getAsAggregate();
1671 if (aggregate->getOp() == EOpSequence)
1677 for (TIntermSequence::iterator sit = aggregate->getSequence().begin(); sit != aggregate->getSequence().end(); sit++)
1679 if (!isSingleStatement(*sit))
1692 // Handle loops with more than 255 iterations (unsupported by D3D9) by splitting them
1693 bool OutputHLSL::handleExcessiveLoop(TIntermLoop *node)
1695 TInfoSinkBase &out = mBody;
1697 // Parse loops of the form:
1698 // for(int index = initial; index [comparator] limit; index += increment)
1699 TIntermSymbol *index = NULL;
1700 TOperator comparator = EOpNull;
1705 // Parse index name and intial value
1706 if (node->getInit())
1708 TIntermAggregate *init = node->getInit()->getAsAggregate();
1712 TIntermSequence &sequence = init->getSequence();
1713 TIntermTyped *variable = sequence[0]->getAsTyped();
1715 if (variable && variable->getQualifier() == EvqTemporary)
1717 TIntermBinary *assign = variable->getAsBinaryNode();
1719 if (assign->getOp() == EOpInitialize)
1721 TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
1722 TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
1724 if (symbol && constant)
1726 if (constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
1729 initial = constant->getUnionArrayPointer()[0].getIConst();
1737 // Parse comparator and limit value
1738 if (index != NULL && node->getCondition())
1740 TIntermBinary *test = node->getCondition()->getAsBinaryNode();
1742 if (test && test->getLeft()->getAsSymbolNode()->getId() == index->getId())
1744 TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
1748 if (constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
1750 comparator = test->getOp();
1751 limit = constant->getUnionArrayPointer()[0].getIConst();
1758 if (index != NULL && comparator != EOpNull && node->getExpression())
1760 TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
1761 TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
1765 TOperator op = binaryTerminal->getOp();
1766 TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
1770 if (constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
1772 int value = constant->getUnionArrayPointer()[0].getIConst();
1776 case EOpAddAssign: increment = value; break;
1777 case EOpSubAssign: increment = -value; break;
1778 default: UNIMPLEMENTED();
1783 else if (unaryTerminal)
1785 TOperator op = unaryTerminal->getOp();
1789 case EOpPostIncrement: increment = 1; break;
1790 case EOpPostDecrement: increment = -1; break;
1791 case EOpPreIncrement: increment = 1; break;
1792 case EOpPreDecrement: increment = -1; break;
1793 default: UNIMPLEMENTED();
1798 if (index != NULL && comparator != EOpNull && increment != 0)
1800 if (comparator == EOpLessThanEqual)
1802 comparator = EOpLessThan;
1806 if (comparator == EOpLessThan)
1808 int iterations = (limit - initial) / increment;
1810 if (iterations <= 255)
1812 return false; // Not an excessive loop
1815 while (iterations > 0)
1817 int remainder = (limit - initial) % increment;
1818 int clampedLimit = initial + increment * std::min(255, iterations);
1820 // for(int index = initial; index < clampedLimit; index += increment)
1823 index->traverse(this);
1828 index->traverse(this);
1830 out << clampedLimit;
1833 index->traverse(this);
1838 outputLineDirective(node->getLine());
1841 if (node->getBody())
1843 node->getBody()->traverse(this);
1846 outputLineDirective(node->getLine());
1849 initial += 255 * increment;
1855 else UNIMPLEMENTED();
1858 return false; // Not handled as an excessive loop
1861 void OutputHLSL::outputTriplet(Visit visit, const TString &preString, const TString &inString, const TString &postString)
1863 TInfoSinkBase &out = mBody;
1865 if (visit == PreVisit)
1869 else if (visit == InVisit)
1873 else if (visit == PostVisit)
1879 void OutputHLSL::outputLineDirective(int line)
1881 if ((mContext.compileOptions & SH_LINE_DIRECTIVES) && (line > 0))
1884 mBody << "#line " << line;
1886 if (mContext.sourcePath)
1888 mBody << " \"" << mContext.sourcePath << "\"";
1895 TString OutputHLSL::argumentString(const TIntermSymbol *symbol)
1897 TQualifier qualifier = symbol->getQualifier();
1898 const TType &type = symbol->getType();
1899 TString name = symbol->getSymbol();
1901 if (name.empty()) // HLSL demands named arguments, also for prototypes
1903 name = "x" + str(mUniqueIndex++);
1907 name = decorate(name);
1910 return qualifierString(qualifier) + " " + typeString(type) + " " + name + arrayString(type);
1913 TString OutputHLSL::qualifierString(TQualifier qualifier)
1917 case EvqIn: return "in";
1918 case EvqOut: return "out";
1919 case EvqInOut: return "inout";
1920 case EvqConstReadOnly: return "const";
1921 default: UNREACHABLE();
1927 TString OutputHLSL::typeString(const TType &type)
1929 if (type.getBasicType() == EbtStruct)
1931 if (type.getTypeName() != "")
1933 return structLookup(type.getTypeName());
1935 else // Nameless structure, define in place
1937 const TTypeList &fields = *type.getStruct();
1939 TString string = "struct\n"
1942 for (unsigned int i = 0; i < fields.size(); i++)
1944 const TType &field = *fields[i].type;
1946 string += " " + typeString(field) + " " + field.getFieldName() + arrayString(field) + ";\n";
1954 else if (type.isMatrix())
1956 switch (type.getNominalSize())
1958 case 2: return "float2x2";
1959 case 3: return "float3x3";
1960 case 4: return "float4x4";
1965 switch (type.getBasicType())
1968 switch (type.getNominalSize())
1970 case 1: return "float";
1971 case 2: return "float2";
1972 case 3: return "float3";
1973 case 4: return "float4";
1976 switch (type.getNominalSize())
1978 case 1: return "int";
1979 case 2: return "int2";
1980 case 3: return "int3";
1981 case 4: return "int4";
1984 switch (type.getNominalSize())
1986 case 1: return "bool";
1987 case 2: return "bool2";
1988 case 3: return "bool3";
1989 case 4: return "bool4";
1995 case EbtSamplerCube:
1996 return "samplerCUBE";
2000 UNIMPLEMENTED(); // FIXME
2001 return "<unknown type>";
2004 TString OutputHLSL::arrayString(const TType &type)
2006 if (!type.isArray())
2011 return "[" + str(type.getArraySize()) + "]";
2014 TString OutputHLSL::initializer(const TType &type)
2018 for (int component = 0; component < type.getObjectSize(); component++)
2022 if (component < type.getObjectSize() - 1)
2028 return "{" + string + "}";
2031 void OutputHLSL::addConstructor(const TType &type, const TString &name, const TIntermSequence *parameters)
2035 return; // Nameless structures don't have constructors
2038 TType ctorType = type;
2039 ctorType.clearArrayness();
2040 ctorType.setPrecision(EbpHigh);
2041 ctorType.setQualifier(EvqTemporary);
2043 TString ctorName = type.getStruct() ? decorate(name) : name;
2045 typedef std::vector<TType> ParameterArray;
2046 ParameterArray ctorParameters;
2050 for (TIntermSequence::const_iterator parameter = parameters->begin(); parameter != parameters->end(); parameter++)
2052 ctorParameters.push_back((*parameter)->getAsTyped()->getType());
2055 else if (type.getStruct())
2057 mStructNames.insert(decorate(name));
2060 structure += "struct " + decorate(name) + "\n"
2063 const TTypeList &fields = *type.getStruct();
2065 for (unsigned int i = 0; i < fields.size(); i++)
2067 const TType &field = *fields[i].type;
2069 structure += " " + typeString(field) + " " + field.getFieldName() + arrayString(field) + ";\n";
2072 structure += "};\n";
2074 if (std::find(mStructDeclarations.begin(), mStructDeclarations.end(), structure) == mStructDeclarations.end())
2076 mStructDeclarations.push_back(structure);
2079 for (unsigned int i = 0; i < fields.size(); i++)
2081 ctorParameters.push_back(*fields[i].type);
2086 TString constructor;
2088 if (ctorType.getStruct())
2090 constructor += ctorName + " " + ctorName + "_ctor(";
2092 else // Built-in type
2094 constructor += typeString(ctorType) + " " + ctorName + "(";
2097 for (unsigned int parameter = 0; parameter < ctorParameters.size(); parameter++)
2099 const TType &type = ctorParameters[parameter];
2101 constructor += typeString(type) + " x" + str(parameter) + arrayString(type);
2103 if (parameter < ctorParameters.size() - 1)
2105 constructor += ", ";
2109 constructor += ")\n"
2112 if (ctorType.getStruct())
2114 constructor += " " + ctorName + " structure = {";
2118 constructor += " return " + typeString(ctorType) + "(";
2121 if (ctorType.isMatrix() && ctorParameters.size() == 1)
2123 int dim = ctorType.getNominalSize();
2124 const TType ¶meter = ctorParameters[0];
2126 if (parameter.isScalar())
2128 for (int row = 0; row < dim; row++)
2130 for (int col = 0; col < dim; col++)
2132 constructor += TString((row == col) ? "x0" : "0.0");
2134 if (row < dim - 1 || col < dim - 1)
2136 constructor += ", ";
2141 else if (parameter.isMatrix())
2143 for (int row = 0; row < dim; row++)
2145 for (int col = 0; col < dim; col++)
2147 if (row < parameter.getNominalSize() && col < parameter.getNominalSize())
2149 constructor += TString("x0") + "[" + str(row) + "]" + "[" + str(col) + "]";
2153 constructor += TString((row == col) ? "1.0" : "0.0");
2156 if (row < dim - 1 || col < dim - 1)
2158 constructor += ", ";
2167 int remainingComponents = ctorType.getObjectSize();
2168 int parameterIndex = 0;
2170 while (remainingComponents > 0)
2172 const TType ¶meter = ctorParameters[parameterIndex];
2173 bool moreParameters = parameterIndex < (int)ctorParameters.size() - 1;
2175 constructor += "x" + str(parameterIndex);
2177 if (parameter.isScalar())
2179 remainingComponents -= parameter.getObjectSize();
2181 else if (parameter.isVector())
2183 if (remainingComponents == parameter.getObjectSize() || moreParameters)
2185 remainingComponents -= parameter.getObjectSize();
2187 else if (remainingComponents < parameter.getNominalSize())
2189 switch (remainingComponents)
2191 case 1: constructor += ".x"; break;
2192 case 2: constructor += ".xy"; break;
2193 case 3: constructor += ".xyz"; break;
2194 case 4: constructor += ".xyzw"; break;
2195 default: UNREACHABLE();
2198 remainingComponents = 0;
2202 else if (parameter.isMatrix() || parameter.getStruct())
2204 ASSERT(remainingComponents == parameter.getObjectSize() || moreParameters);
2206 remainingComponents -= parameter.getObjectSize();
2215 if (remainingComponents)
2217 constructor += ", ";
2222 if (ctorType.getStruct())
2224 constructor += "};\n"
2225 " return structure;\n"
2230 constructor += ");\n"
2234 mConstructors.insert(constructor);
2237 const ConstantUnion *OutputHLSL::writeConstantUnion(const TType &type, const ConstantUnion *constUnion)
2239 TInfoSinkBase &out = mBody;
2241 if (type.getBasicType() == EbtStruct)
2243 out << structLookup(type.getTypeName()) + "_ctor(";
2245 const TTypeList *structure = type.getStruct();
2247 for (size_t i = 0; i < structure->size(); i++)
2249 const TType *fieldType = (*structure)[i].type;
2251 constUnion = writeConstantUnion(*fieldType, constUnion);
2253 if (i != structure->size() - 1)
2263 int size = type.getObjectSize();
2264 bool writeType = size > 1;
2268 out << typeString(type) << "(";
2271 for (int i = 0; i < size; i++, constUnion++)
2273 switch (constUnion->getType())
2275 case EbtFloat: out << constUnion->getFConst(); break;
2276 case EbtInt: out << constUnion->getIConst(); break;
2277 case EbtBool: out << constUnion->getBConst(); break;
2278 default: UNREACHABLE();
2296 TString OutputHLSL::scopeString(unsigned int depthLimit)
2300 for (unsigned int i = 0; i < mScopeBracket.size() && i < depthLimit; i++)
2302 string += "_" + str(i);
2308 TString OutputHLSL::scopedStruct(const TString &typeName)
2315 return typeName + scopeString(mScopeDepth);
2318 TString OutputHLSL::structLookup(const TString &typeName)
2320 for (int depth = mScopeDepth; depth >= 0; depth--)
2322 TString scopedName = decorate(typeName + scopeString(depth));
2324 for (StructNames::iterator structName = mStructNames.begin(); structName != mStructNames.end(); structName++)
2326 if (*structName == scopedName)
2333 UNREACHABLE(); // Should have found a matching constructor
2338 TString OutputHLSL::decorate(const TString &string)
2340 if (string.substr(0, 3) != "gl_" && string.substr(0, 3) != "dx_")
2342 return "_" + string;