1 //
2 // Copyright 2014 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.
5 //
6 // DynamicHLSL.cpp: Implementation for link and run-time HLSL generation
7 //
8
9 #include "libANGLE/renderer/d3d/DynamicHLSL.h"
10
11 #include "common/string_utils.h"
12 #include "common/utilities.h"
13 #include "compiler/translator/blocklayoutHLSL.h"
14 #include "libANGLE/Context.h"
15 #include "libANGLE/Program.h"
16 #include "libANGLE/Shader.h"
17 #include "libANGLE/VaryingPacking.h"
18 #include "libANGLE/formatutils.h"
19 #include "libANGLE/renderer/d3d/ProgramD3D.h"
20 #include "libANGLE/renderer/d3d/RendererD3D.h"
21 #include "libANGLE/renderer/d3d/ShaderD3D.h"
22
23 using namespace gl;
24
25 namespace rx
26 {
27
28 namespace
29 {
30
HLSLComponentTypeString(GLenum componentType)31 const char *HLSLComponentTypeString(GLenum componentType)
32 {
33 switch (componentType)
34 {
35 case GL_UNSIGNED_INT:
36 return "uint";
37 case GL_INT:
38 return "int";
39 case GL_UNSIGNED_NORMALIZED:
40 case GL_SIGNED_NORMALIZED:
41 case GL_FLOAT:
42 return "float";
43 default:
44 UNREACHABLE();
45 return "not-component-type";
46 }
47 }
48
HLSLComponentTypeString(std::ostringstream & ostream,GLenum componentType,int componentCount)49 void HLSLComponentTypeString(std::ostringstream &ostream, GLenum componentType, int componentCount)
50 {
51 ostream << HLSLComponentTypeString(componentType);
52 if (componentCount > 1)
53 {
54 ostream << componentCount;
55 }
56 }
57
HLSLMatrixTypeString(GLenum type)58 const char *HLSLMatrixTypeString(GLenum type)
59 {
60 switch (type)
61 {
62 case GL_FLOAT_MAT2:
63 return "float2x2";
64 case GL_FLOAT_MAT3:
65 return "float3x3";
66 case GL_FLOAT_MAT4:
67 return "float4x4";
68 case GL_FLOAT_MAT2x3:
69 return "float2x3";
70 case GL_FLOAT_MAT3x2:
71 return "float3x2";
72 case GL_FLOAT_MAT2x4:
73 return "float2x4";
74 case GL_FLOAT_MAT4x2:
75 return "float4x2";
76 case GL_FLOAT_MAT3x4:
77 return "float3x4";
78 case GL_FLOAT_MAT4x3:
79 return "float4x3";
80 default:
81 UNREACHABLE();
82 return "not-matrix-type";
83 }
84 }
85
HLSLTypeString(std::ostringstream & ostream,GLenum type)86 void HLSLTypeString(std::ostringstream &ostream, GLenum type)
87 {
88 if (gl::IsMatrixType(type))
89 {
90 ostream << HLSLMatrixTypeString(type);
91 return;
92 }
93
94 HLSLComponentTypeString(ostream, gl::VariableComponentType(type),
95 gl::VariableComponentCount(type));
96 }
97
FindOutputAtLocation(const std::vector<PixelShaderOutputVariable> & outputVariables,unsigned int location,size_t index=0)98 const PixelShaderOutputVariable *FindOutputAtLocation(
99 const std::vector<PixelShaderOutputVariable> &outputVariables,
100 unsigned int location,
101 size_t index = 0)
102 {
103 for (auto &outputVar : outputVariables)
104 {
105 if (outputVar.outputLocation == location && outputVar.outputIndex == index)
106 {
107 return &outputVar;
108 }
109 }
110
111 return nullptr;
112 }
113
WriteArrayString(std::ostringstream & strstr,unsigned int i)114 void WriteArrayString(std::ostringstream &strstr, unsigned int i)
115 {
116 static_assert(GL_INVALID_INDEX == UINT_MAX,
117 "GL_INVALID_INDEX must be equal to the max unsigned int.");
118 if (i == UINT_MAX)
119 {
120 return;
121 }
122
123 strstr << "[";
124 strstr << i;
125 strstr << "]";
126 }
127
128 constexpr const char *VERTEX_ATTRIBUTE_STUB_STRING = "@@ VERTEX ATTRIBUTES @@";
129 constexpr const char *VERTEX_OUTPUT_STUB_STRING = "@@ VERTEX OUTPUT @@";
130 constexpr const char *PIXEL_OUTPUT_STUB_STRING = "@@ PIXEL OUTPUT @@";
131 constexpr const char *PIXEL_MAIN_PARAMETERS_STUB_STRING = "@@ PIXEL MAIN PARAMETERS @@";
132 constexpr const char *MAIN_PROLOGUE_STUB_STRING = "@@ MAIN PROLOGUE @@";
133 } // anonymous namespace
134
135 // BuiltinInfo implementation
136
137 BuiltinInfo::BuiltinInfo() = default;
138 BuiltinInfo::~BuiltinInfo() = default;
139
140 // DynamicHLSL implementation
141
DynamicHLSL(RendererD3D * const renderer)142 DynamicHLSL::DynamicHLSL(RendererD3D *const renderer) : mRenderer(renderer) {}
143
generateVertexShaderForInputLayout(const std::string & sourceShader,const InputLayout & inputLayout,const std::vector<sh::ShaderVariable> & shaderAttributes) const144 std::string DynamicHLSL::generateVertexShaderForInputLayout(
145 const std::string &sourceShader,
146 const InputLayout &inputLayout,
147 const std::vector<sh::ShaderVariable> &shaderAttributes) const
148 {
149 std::ostringstream structStream;
150 std::ostringstream initStream;
151
152 structStream << "struct VS_INPUT\n"
153 << "{\n";
154
155 int semanticIndex = 0;
156 unsigned int inputIndex = 0;
157
158 // If gl_PointSize is used in the shader then pointsprites rendering is expected.
159 // If the renderer does not support Geometry shaders then Instanced PointSprite emulation
160 // must be used.
161 bool usesPointSize = sourceShader.find("GL_USES_POINT_SIZE") != std::string::npos;
162 bool useInstancedPointSpriteEmulation =
163 usesPointSize && mRenderer->getFeatures().useInstancedPointSpriteEmulation.enabled;
164
165 // Instanced PointSprite emulation requires additional entries in the
166 // VS_INPUT structure to support the vertices that make up the quad vertices.
167 // These values must be in sync with the cooresponding values added during inputlayout creation
168 // in InputLayoutCache::applyVertexBuffers().
169 //
170 // The additional entries must appear first in the VS_INPUT layout because
171 // Windows Phone 8 era devices require per vertex data to physically come
172 // before per instance data in the shader.
173 if (useInstancedPointSpriteEmulation)
174 {
175 structStream << " float3 spriteVertexPos : SPRITEPOSITION0;\n"
176 << " float2 spriteTexCoord : SPRITETEXCOORD0;\n";
177 }
178
179 for (size_t attributeIndex = 0; attributeIndex < shaderAttributes.size(); ++attributeIndex)
180 {
181 const sh::ShaderVariable &shaderAttribute = shaderAttributes[attributeIndex];
182 if (!shaderAttribute.name.empty())
183 {
184 ASSERT(inputIndex < MAX_VERTEX_ATTRIBS);
185 angle::FormatID vertexFormatID =
186 inputIndex < inputLayout.size() ? inputLayout[inputIndex] : angle::FormatID::NONE;
187
188 // HLSL code for input structure
189 if (IsMatrixType(shaderAttribute.type))
190 {
191 // Matrix types are always transposed
192 structStream << " "
193 << HLSLMatrixTypeString(TransposeMatrixType(shaderAttribute.type));
194 }
195 else
196 {
197 if (shaderAttribute.name == "gl_InstanceID" ||
198 shaderAttribute.name == "gl_VertexID")
199 {
200 // The input types of the instance ID and vertex ID in HLSL (uint) differs from
201 // the ones in ESSL (int).
202 structStream << " uint";
203 }
204 else
205 {
206 GLenum componentType = mRenderer->getVertexComponentType(vertexFormatID);
207
208 structStream << " ";
209 HLSLComponentTypeString(structStream, componentType,
210 VariableComponentCount(shaderAttribute.type));
211 }
212 }
213
214 structStream << " " << DecorateVariable(shaderAttribute.name) << " : ";
215
216 if (shaderAttribute.name == "gl_InstanceID")
217 {
218 structStream << "SV_InstanceID";
219 }
220 else if (shaderAttribute.name == "gl_VertexID")
221 {
222 structStream << "SV_VertexID";
223 }
224 else
225 {
226 structStream << "TEXCOORD" << semanticIndex;
227 semanticIndex += VariableRegisterCount(shaderAttribute.type);
228 }
229
230 structStream << ";\n";
231
232 // HLSL code for initialization
233 initStream << " " << DecorateVariable(shaderAttribute.name) << " = ";
234
235 // Mismatched vertex attribute to vertex input may result in an undefined
236 // data reinterpretation (eg for pure integer->float, float->pure integer)
237 // TODO: issue warning with gl debug info extension, when supported
238 if (IsMatrixType(shaderAttribute.type) ||
239 (mRenderer->getVertexConversionType(vertexFormatID) & VERTEX_CONVERT_GPU) != 0)
240 {
241 GenerateAttributeConversionHLSL(vertexFormatID, shaderAttribute, initStream);
242 }
243 else
244 {
245 initStream << "input." << DecorateVariable(shaderAttribute.name);
246 }
247
248 if (shaderAttribute.name == "gl_VertexID")
249 {
250 // dx_VertexID contains the firstVertex offset
251 initStream << " + dx_VertexID";
252 }
253
254 initStream << ";\n";
255
256 inputIndex += VariableRowCount(TransposeMatrixType(shaderAttribute.type));
257 }
258 }
259
260 structStream << "};\n"
261 "\n"
262 "void initAttributes(VS_INPUT input)\n"
263 "{\n"
264 << initStream.str() << "}\n";
265
266 std::string vertexHLSL(sourceShader);
267
268 bool success =
269 angle::ReplaceSubstring(&vertexHLSL, VERTEX_ATTRIBUTE_STUB_STRING, structStream.str());
270 ASSERT(success);
271
272 return vertexHLSL;
273 }
274
generatePixelShaderForOutputSignature(const std::string & sourceShader,const std::vector<PixelShaderOutputVariable> & outputVariables,bool usesFragDepth,const std::vector<GLenum> & outputLayout) const275 std::string DynamicHLSL::generatePixelShaderForOutputSignature(
276 const std::string &sourceShader,
277 const std::vector<PixelShaderOutputVariable> &outputVariables,
278 bool usesFragDepth,
279 const std::vector<GLenum> &outputLayout) const
280 {
281 const int shaderModel = mRenderer->getMajorShaderModel();
282 std::string targetSemantic = (shaderModel >= 4) ? "SV_TARGET" : "COLOR";
283 std::string depthSemantic = (shaderModel >= 4) ? "SV_Depth" : "DEPTH";
284
285 std::ostringstream declarationStream;
286 std::ostringstream copyStream;
287
288 declarationStream << "struct PS_OUTPUT\n"
289 "{\n";
290
291 size_t numOutputs = outputLayout.size();
292
293 // Workaround for HLSL 3.x: We can't do a depth/stencil only render, the runtime will complain.
294 if (numOutputs == 0 && (shaderModel == 3 || !mRenderer->getShaderModelSuffix().empty()))
295 {
296 numOutputs = 1u;
297 }
298 const PixelShaderOutputVariable defaultOutput(GL_FLOAT_VEC4, "unused", "float4(0, 0, 0, 1)", 0,
299 0);
300 size_t outputIndex = 0;
301
302 for (size_t layoutIndex = 0; layoutIndex < numOutputs; ++layoutIndex)
303 {
304 GLenum binding = outputLayout.empty() ? GL_COLOR_ATTACHMENT0 : outputLayout[layoutIndex];
305
306 if (binding != GL_NONE)
307 {
308 unsigned int location = (binding - GL_COLOR_ATTACHMENT0);
309 outputIndex =
310 layoutIndex > 0 && binding == outputLayout[layoutIndex - 1] ? outputIndex + 1 : 0;
311
312 const PixelShaderOutputVariable *outputVariable =
313 outputLayout.empty() ? &defaultOutput
314 : FindOutputAtLocation(outputVariables, location, outputIndex);
315
316 // OpenGL ES 3.0 spec $4.2.1
317 // If [...] not all user-defined output variables are written, the values of fragment
318 // colors corresponding to unwritten variables are similarly undefined.
319 if (outputVariable)
320 {
321 declarationStream << " ";
322 HLSLTypeString(declarationStream, outputVariable->type);
323 declarationStream << " " << outputVariable->name << " : " << targetSemantic
324 << static_cast<int>(layoutIndex) << ";\n";
325
326 copyStream << " output." << outputVariable->name << " = "
327 << outputVariable->source << ";\n";
328 }
329 }
330 }
331
332 if (usesFragDepth)
333 {
334 declarationStream << " float gl_Depth : " << depthSemantic << ";\n";
335 copyStream << " output.gl_Depth = gl_Depth; \n";
336 }
337
338 declarationStream << "};\n"
339 "\n"
340 "PS_OUTPUT generateOutput()\n"
341 "{\n"
342 " PS_OUTPUT output;\n"
343 << copyStream.str()
344 << " return output;\n"
345 "}\n";
346
347 std::string pixelHLSL(sourceShader);
348
349 bool success =
350 angle::ReplaceSubstring(&pixelHLSL, PIXEL_OUTPUT_STUB_STRING, declarationStream.str());
351 ASSERT(success);
352
353 return pixelHLSL;
354 }
355
generateComputeShaderForImage2DBindSignature(const d3d::Context * context,ProgramD3D & programD3D,const gl::ProgramState & programData,std::vector<sh::ShaderVariable> & image2DUniforms,const gl::ImageUnitTextureTypeMap & image2DBindLayout) const356 std::string DynamicHLSL::generateComputeShaderForImage2DBindSignature(
357 const d3d::Context *context,
358 ProgramD3D &programD3D,
359 const gl::ProgramState &programData,
360 std::vector<sh::ShaderVariable> &image2DUniforms,
361 const gl::ImageUnitTextureTypeMap &image2DBindLayout) const
362 {
363 std::string computeHLSL(
364 programData.getAttachedShader(ShaderType::Compute)->getTranslatedSource());
365
366 if (image2DUniforms.empty())
367 {
368 return computeHLSL;
369 }
370
371 return GenerateComputeShaderForImage2DBindSignature(context, programD3D, programData,
372 image2DUniforms, image2DBindLayout);
373 }
374
generateVaryingLinkHLSL(const VaryingPacking & varyingPacking,const BuiltinInfo & builtins,bool programUsesPointSize,std::ostringstream & hlslStream) const375 void DynamicHLSL::generateVaryingLinkHLSL(const VaryingPacking &varyingPacking,
376 const BuiltinInfo &builtins,
377 bool programUsesPointSize,
378 std::ostringstream &hlslStream) const
379 {
380 ASSERT(builtins.dxPosition.enabled);
381 hlslStream << "{\n"
382 << " float4 dx_Position : " << builtins.dxPosition.str() << ";\n";
383
384 if (builtins.glPosition.enabled)
385 {
386 hlslStream << " float4 gl_Position : " << builtins.glPosition.str() << ";\n";
387 }
388
389 if (builtins.glFragCoord.enabled)
390 {
391 hlslStream << " float4 gl_FragCoord : " << builtins.glFragCoord.str() << ";\n";
392 }
393
394 if (builtins.glPointCoord.enabled)
395 {
396 hlslStream << " float2 gl_PointCoord : " << builtins.glPointCoord.str() << ";\n";
397 }
398
399 if (builtins.glPointSize.enabled)
400 {
401 hlslStream << " float gl_PointSize : " << builtins.glPointSize.str() << ";\n";
402 }
403
404 if (builtins.glViewIDOVR.enabled)
405 {
406 hlslStream << " nointerpolation uint gl_ViewID_OVR : " << builtins.glViewIDOVR.str()
407 << ";\n";
408 }
409
410 std::string varyingSemantic =
411 GetVaryingSemantic(mRenderer->getMajorShaderModel(), programUsesPointSize);
412
413 const auto ®isterInfos = varyingPacking.getRegisterList();
414 for (GLuint registerIndex = 0u; registerIndex < registerInfos.size(); ++registerIndex)
415 {
416 const PackedVaryingRegister ®isterInfo = registerInfos[registerIndex];
417 const auto &varying = registerInfo.packedVarying->varying();
418 ASSERT(!varying.isStruct());
419
420 // TODO: Add checks to ensure D3D interpolation modifiers don't result in too many
421 // registers being used.
422 // For example, if there are N registers, and we have N vec3 varyings and 1 float
423 // varying, then D3D will pack them into N registers.
424 // If the float varying has the 'nointerpolation' modifier on it then we would need
425 // N + 1 registers, and D3D compilation will fail.
426
427 switch (registerInfo.packedVarying->interpolation)
428 {
429 case sh::INTERPOLATION_SMOOTH:
430 hlslStream << " ";
431 break;
432 case sh::INTERPOLATION_FLAT:
433 hlslStream << " nointerpolation ";
434 break;
435 case sh::INTERPOLATION_CENTROID:
436 hlslStream << " centroid ";
437 break;
438 case sh::INTERPOLATION_SAMPLE:
439 hlslStream << " sample ";
440 break;
441 default:
442 UNREACHABLE();
443 }
444
445 GLenum transposedType = gl::TransposeMatrixType(varying.type);
446 GLenum componentType = gl::VariableComponentType(transposedType);
447 int columnCount = gl::VariableColumnCount(transposedType);
448 HLSLComponentTypeString(hlslStream, componentType, columnCount);
449 hlslStream << " v" << registerIndex << " : " << varyingSemantic << registerIndex << ";\n";
450 }
451
452 // Note that the following outputs need to be declared after the others. They are not included
453 // in pixel shader inputs even when they are in vertex/geometry shader outputs, and the pixel
454 // shader input struct must be a prefix of the vertex/geometry shader output struct.
455
456 if (builtins.glViewportIndex.enabled)
457 {
458 hlslStream << " nointerpolation uint gl_ViewportIndex : "
459 << builtins.glViewportIndex.str() << ";\n";
460 }
461
462 if (builtins.glLayer.enabled)
463 {
464 hlslStream << " nointerpolation uint gl_Layer : " << builtins.glLayer.str() << ";\n";
465 }
466
467 hlslStream << "};\n";
468 }
469
generateShaderLinkHLSL(const gl::Caps & caps,const gl::ProgramState & programData,const ProgramD3DMetadata & programMetadata,const VaryingPacking & varyingPacking,const BuiltinVaryingsD3D & builtinsD3D,gl::ShaderMap<std::string> * shaderHLSL) const470 void DynamicHLSL::generateShaderLinkHLSL(const gl::Caps &caps,
471 const gl::ProgramState &programData,
472 const ProgramD3DMetadata &programMetadata,
473 const VaryingPacking &varyingPacking,
474 const BuiltinVaryingsD3D &builtinsD3D,
475 gl::ShaderMap<std::string> *shaderHLSL) const
476 {
477 ASSERT(shaderHLSL);
478 ASSERT((*shaderHLSL)[gl::ShaderType::Vertex].empty() &&
479 (*shaderHLSL)[gl::ShaderType::Fragment].empty());
480
481 gl::Shader *vertexShaderGL = programData.getAttachedShader(ShaderType::Vertex);
482 gl::Shader *fragmentShaderGL = programData.getAttachedShader(ShaderType::Fragment);
483 const int shaderModel = mRenderer->getMajorShaderModel();
484
485 const ShaderD3D *fragmentShader = nullptr;
486 if (fragmentShaderGL)
487 {
488 fragmentShader = GetImplAs<ShaderD3D>(fragmentShaderGL);
489 }
490
491 // usesViewScale() isn't supported in the D3D9 renderer
492 ASSERT(shaderModel >= 4 || !programMetadata.usesViewScale());
493
494 bool useInstancedPointSpriteEmulation =
495 programMetadata.usesPointSize() &&
496 mRenderer->getFeatures().useInstancedPointSpriteEmulation.enabled;
497
498 // Validation done in the compiler
499 ASSERT(!fragmentShader || !fragmentShader->usesFragColor() || !fragmentShader->usesFragData());
500
501 std::ostringstream vertexStream;
502 vertexStream << "struct VS_OUTPUT\n";
503 const auto &vertexBuiltins = builtinsD3D[gl::ShaderType::Vertex];
504 generateVaryingLinkHLSL(varyingPacking, vertexBuiltins, builtinsD3D.usesPointSize(),
505 vertexStream);
506
507 // Instanced PointSprite emulation requires additional entries originally generated in the
508 // GeometryShader HLSL. These include pointsize clamp values.
509 if (useInstancedPointSpriteEmulation)
510 {
511 vertexStream << "static float minPointSize = " << static_cast<int>(caps.minAliasedPointSize)
512 << ".0f;\n"
513 << "static float maxPointSize = " << static_cast<int>(caps.maxAliasedPointSize)
514 << ".0f;\n";
515 }
516
517 std::ostringstream vertexGenerateOutput;
518 vertexGenerateOutput << "VS_OUTPUT generateOutput(VS_INPUT input)\n"
519 << "{\n"
520 << " VS_OUTPUT output;\n";
521
522 if (vertexBuiltins.glPosition.enabled)
523 {
524 vertexGenerateOutput << " output.gl_Position = gl_Position;\n";
525 }
526
527 if (vertexBuiltins.glViewIDOVR.enabled)
528 {
529 vertexGenerateOutput << " output.gl_ViewID_OVR = ViewID_OVR;\n";
530 }
531 if (programMetadata.hasANGLEMultiviewEnabled() && programMetadata.canSelectViewInVertexShader())
532 {
533 ASSERT(vertexBuiltins.glViewportIndex.enabled && vertexBuiltins.glLayer.enabled);
534 vertexGenerateOutput << " if (multiviewSelectViewportIndex)\n"
535 << " {\n"
536 << " output.gl_ViewportIndex = ViewID_OVR;\n"
537 << " } else {\n"
538 << " output.gl_ViewportIndex = 0;\n"
539 << " output.gl_Layer = ViewID_OVR;\n"
540 << " }\n";
541 }
542
543 // On D3D9 or D3D11 Feature Level 9, we need to emulate large viewports using dx_ViewAdjust.
544 if (shaderModel >= 4 && mRenderer->getShaderModelSuffix() == "")
545 {
546 vertexGenerateOutput << " output.dx_Position.x = gl_Position.x;\n";
547
548 if (programMetadata.usesViewScale())
549 {
550 // This code assumes that dx_ViewScale.y = -1.0f when rendering to texture, and +1.0f
551 // when rendering to the default framebuffer. No other values are valid.
552 vertexGenerateOutput << " output.dx_Position.y = dx_ViewScale.y * gl_Position.y;\n";
553 }
554 else
555 {
556 vertexGenerateOutput << " output.dx_Position.y = - gl_Position.y;\n";
557 }
558
559 vertexGenerateOutput
560 << " output.dx_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n"
561 << " output.dx_Position.w = gl_Position.w;\n";
562 }
563 else
564 {
565 vertexGenerateOutput << " output.dx_Position.x = gl_Position.x * dx_ViewAdjust.z + "
566 "dx_ViewAdjust.x * gl_Position.w;\n";
567
568 // If usesViewScale() is true and we're using the D3D11 renderer via Feature Level 9_*,
569 // then we need to multiply the gl_Position.y by the viewScale.
570 // usesViewScale() isn't supported when using the D3D9 renderer.
571 if (programMetadata.usesViewScale() &&
572 (shaderModel >= 4 && mRenderer->getShaderModelSuffix() != ""))
573 {
574 vertexGenerateOutput << " output.dx_Position.y = dx_ViewScale.y * (gl_Position.y * "
575 "dx_ViewAdjust.w + dx_ViewAdjust.y * gl_Position.w);\n";
576 }
577 else
578 {
579 vertexGenerateOutput
580 << " output.dx_Position.y = -(gl_Position.y * dx_ViewAdjust.w + "
581 "dx_ViewAdjust.y * gl_Position.w);\n";
582 }
583
584 vertexGenerateOutput
585 << " output.dx_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n"
586 << " output.dx_Position.w = gl_Position.w;\n";
587 }
588
589 // We don't need to output gl_PointSize if we use are emulating point sprites via instancing.
590 if (vertexBuiltins.glPointSize.enabled)
591 {
592 vertexGenerateOutput << " output.gl_PointSize = gl_PointSize;\n";
593 }
594
595 if (vertexBuiltins.glFragCoord.enabled)
596 {
597 vertexGenerateOutput << " output.gl_FragCoord = gl_Position;\n";
598 }
599
600 const auto ®isterInfos = varyingPacking.getRegisterList();
601 for (GLuint registerIndex = 0u; registerIndex < registerInfos.size(); ++registerIndex)
602 {
603 const PackedVaryingRegister ®isterInfo = registerInfos[registerIndex];
604 const auto &packedVarying = *registerInfo.packedVarying;
605 const auto &varying = *packedVarying.frontVarying.varying;
606 ASSERT(!varying.isStruct());
607
608 vertexGenerateOutput << " output.v" << registerIndex << " = ";
609
610 if (packedVarying.isStructField())
611 {
612 vertexGenerateOutput << DecorateVariable(packedVarying.frontVarying.parentStructName)
613 << ".";
614 }
615
616 vertexGenerateOutput << DecorateVariable(varying.name);
617
618 if (varying.isArray())
619 {
620 WriteArrayString(vertexGenerateOutput, registerInfo.varyingArrayIndex);
621 }
622
623 if (VariableRowCount(varying.type) > 1)
624 {
625 WriteArrayString(vertexGenerateOutput, registerInfo.varyingRowIndex);
626 }
627
628 vertexGenerateOutput << ";\n";
629 }
630
631 // Instanced PointSprite emulation requires additional entries to calculate
632 // the final output vertex positions of the quad that represents each sprite.
633 if (useInstancedPointSpriteEmulation)
634 {
635 vertexGenerateOutput
636 << "\n"
637 << " gl_PointSize = clamp(gl_PointSize, minPointSize, maxPointSize);\n";
638
639 vertexGenerateOutput
640 << " output.dx_Position.x += (input.spriteVertexPos.x * gl_PointSize / "
641 "(dx_ViewCoords.x*2)) * output.dx_Position.w;";
642
643 if (programMetadata.usesViewScale())
644 {
645 // Multiply by ViewScale to invert the rendering when appropriate
646 vertexGenerateOutput
647 << " output.dx_Position.y += (-dx_ViewScale.y * "
648 "input.spriteVertexPos.y * gl_PointSize / (dx_ViewCoords.y*2)) * "
649 "output.dx_Position.w;";
650 }
651 else
652 {
653 vertexGenerateOutput
654 << " output.dx_Position.y += (input.spriteVertexPos.y * gl_PointSize / "
655 "(dx_ViewCoords.y*2)) * output.dx_Position.w;";
656 }
657
658 vertexGenerateOutput
659 << " output.dx_Position.z += input.spriteVertexPos.z * output.dx_Position.w;\n";
660
661 if (programMetadata.usesPointCoord())
662 {
663 vertexGenerateOutput << "\n"
664 << " output.gl_PointCoord = input.spriteTexCoord;\n";
665 }
666 }
667
668 // Renderers that enable instanced pointsprite emulation require the vertex shader output member
669 // gl_PointCoord to be set to a default value if used without gl_PointSize. 0.5,0.5 is the same
670 // default value used in the generated pixel shader.
671 if (programMetadata.usesInsertedPointCoordValue())
672 {
673 ASSERT(!useInstancedPointSpriteEmulation);
674 vertexGenerateOutput << "\n"
675 << " output.gl_PointCoord = float2(0.5, 0.5);\n";
676 }
677
678 vertexGenerateOutput << "\n"
679 << " return output;\n"
680 << "}";
681
682 if (vertexShaderGL)
683 {
684 std::string vertexSource = vertexShaderGL->getTranslatedSource();
685 angle::ReplaceSubstring(&vertexSource, std::string(MAIN_PROLOGUE_STUB_STRING),
686 " initAttributes(input);\n");
687 angle::ReplaceSubstring(&vertexSource, std::string(VERTEX_OUTPUT_STUB_STRING),
688 vertexGenerateOutput.str());
689 vertexStream << vertexSource;
690 }
691
692 const auto &pixelBuiltins = builtinsD3D[gl::ShaderType::Fragment];
693
694 std::ostringstream pixelStream;
695 pixelStream << "struct PS_INPUT\n";
696 generateVaryingLinkHLSL(varyingPacking, pixelBuiltins, builtinsD3D.usesPointSize(),
697 pixelStream);
698 pixelStream << "\n";
699
700 std::ostringstream pixelPrologue;
701 if (fragmentShader && fragmentShader->usesViewID())
702 {
703 ASSERT(pixelBuiltins.glViewIDOVR.enabled);
704 pixelPrologue << " ViewID_OVR = input.gl_ViewID_OVR;\n";
705 }
706
707 if (pixelBuiltins.glFragCoord.enabled)
708 {
709 pixelPrologue << " float rhw = 1.0 / input.gl_FragCoord.w;\n";
710
711 // Certain Shader Models (4_0+ and 3_0) allow reading from dx_Position in the pixel shader.
712 // Other Shader Models (4_0_level_9_3 and 2_x) don't support this, so we emulate it using
713 // dx_ViewCoords.
714 if (shaderModel >= 4 && mRenderer->getShaderModelSuffix() == "")
715 {
716 pixelPrologue << " gl_FragCoord.x = input.dx_Position.x;\n"
717 << " gl_FragCoord.y = input.dx_Position.y;\n";
718 }
719 else if (shaderModel == 3)
720 {
721 pixelPrologue << " gl_FragCoord.x = input.dx_Position.x + 0.5;\n"
722 << " gl_FragCoord.y = input.dx_Position.y + 0.5;\n";
723 }
724 else
725 {
726 // dx_ViewCoords contains the viewport width/2, height/2, center.x and center.y. See
727 // Renderer::setViewport()
728 pixelPrologue
729 << " gl_FragCoord.x = (input.gl_FragCoord.x * rhw) * dx_ViewCoords.x + "
730 "dx_ViewCoords.z;\n"
731 << " gl_FragCoord.y = (input.gl_FragCoord.y * rhw) * dx_ViewCoords.y + "
732 "dx_ViewCoords.w;\n";
733 }
734
735 if (programMetadata.usesViewScale())
736 {
737 // For Feature Level 9_3 and below, we need to correct gl_FragCoord.y to account
738 // for dx_ViewScale. On Feature Level 10_0+, gl_FragCoord.y is calculated above using
739 // dx_ViewCoords and is always correct irrespective of dx_ViewScale's value.
740 // NOTE: usesViewScale() can only be true on D3D11 (i.e. Shader Model 4.0+).
741 if (shaderModel >= 4 && mRenderer->getShaderModelSuffix() == "")
742 {
743 // Some assumptions:
744 // - dx_ViewScale.y = -1.0f when rendering to texture
745 // - dx_ViewScale.y = +1.0f when rendering to the default framebuffer
746 // - gl_FragCoord.y has been set correctly above.
747 //
748 // When rendering to the backbuffer, the code inverts gl_FragCoord's y coordinate.
749 // This involves subtracting the y coordinate from the height of the area being
750 // rendered to.
751 //
752 // First we calculate the height of the area being rendered to:
753 // render_area_height = (2.0f / (1.0f - input.gl_FragCoord.y * rhw)) *
754 // gl_FragCoord.y
755 //
756 // Note that when we're rendering to default FB, we want our output to be
757 // equivalent to:
758 // "gl_FragCoord.y = render_area_height - gl_FragCoord.y"
759 //
760 // When we're rendering to a texture, we want our output to be equivalent to:
761 // "gl_FragCoord.y = gl_FragCoord.y;"
762 //
763 // If we set scale_factor = ((1.0f + dx_ViewScale.y) / 2.0f), then notice that
764 // - When rendering to default FB: scale_factor = 1.0f
765 // - When rendering to texture: scale_factor = 0.0f
766 //
767 // Therefore, we can get our desired output by setting:
768 // "gl_FragCoord.y = scale_factor * render_area_height - dx_ViewScale.y *
769 // gl_FragCoord.y"
770 //
771 // Simplifying, this becomes:
772 pixelPrologue
773 << " gl_FragCoord.y = (1.0f + dx_ViewScale.y) * gl_FragCoord.y /"
774 "(1.0f - input.gl_FragCoord.y * rhw) - dx_ViewScale.y * gl_FragCoord.y;\n";
775 }
776 }
777
778 pixelPrologue << " gl_FragCoord.z = (input.gl_FragCoord.z * rhw) * dx_DepthFront.x + "
779 "dx_DepthFront.y;\n"
780 << " gl_FragCoord.w = rhw;\n";
781 }
782
783 if (pixelBuiltins.glPointCoord.enabled && shaderModel >= 3)
784 {
785 pixelPrologue << " gl_PointCoord.x = input.gl_PointCoord.x;\n"
786 << " gl_PointCoord.y = 1.0 - input.gl_PointCoord.y;\n";
787 }
788
789 if (fragmentShader && fragmentShader->usesFrontFacing())
790 {
791 if (shaderModel <= 3)
792 {
793 pixelPrologue << " gl_FrontFacing = (vFace * dx_DepthFront.z >= 0.0);\n";
794 }
795 else
796 {
797 pixelPrologue << " gl_FrontFacing = isFrontFace;\n";
798 }
799 }
800
801 for (GLuint registerIndex = 0u; registerIndex < registerInfos.size(); ++registerIndex)
802 {
803 const PackedVaryingRegister ®isterInfo = registerInfos[registerIndex];
804 const auto &packedVarying = *registerInfo.packedVarying;
805
806 // Don't reference VS-only transform feedback varyings in the PS.
807 if (packedVarying.vertexOnly())
808 {
809 continue;
810 }
811
812 const auto &varying = *packedVarying.backVarying.varying;
813 ASSERT(!varying.isBuiltIn() && !varying.isStruct());
814
815 // Note that we're relying on that the active flag is set according to usage in the fragment
816 // shader.
817 if (!varying.active)
818 {
819 continue;
820 }
821
822 pixelPrologue << " ";
823
824 if (packedVarying.isStructField())
825 {
826 pixelPrologue << DecorateVariable(packedVarying.backVarying.parentStructName) << ".";
827 }
828
829 pixelPrologue << DecorateVariable(varying.name);
830
831 if (varying.isArray())
832 {
833 WriteArrayString(pixelPrologue, registerInfo.varyingArrayIndex);
834 }
835
836 GLenum transposedType = TransposeMatrixType(varying.type);
837 if (VariableRowCount(transposedType) > 1)
838 {
839 WriteArrayString(pixelPrologue, registerInfo.varyingRowIndex);
840 }
841
842 pixelPrologue << " = input.v" << registerIndex;
843
844 switch (VariableColumnCount(transposedType))
845 {
846 case 1:
847 pixelPrologue << ".x";
848 break;
849 case 2:
850 pixelPrologue << ".xy";
851 break;
852 case 3:
853 pixelPrologue << ".xyz";
854 break;
855 case 4:
856 break;
857 default:
858 UNREACHABLE();
859 }
860 pixelPrologue << ";\n";
861 }
862
863 if (fragmentShaderGL)
864 {
865 std::string pixelSource = fragmentShaderGL->getTranslatedSource();
866
867 if (fragmentShader->usesFrontFacing())
868 {
869 if (shaderModel >= 4)
870 {
871 angle::ReplaceSubstring(&pixelSource,
872 std::string(PIXEL_MAIN_PARAMETERS_STUB_STRING),
873 "PS_INPUT input, bool isFrontFace : SV_IsFrontFace");
874 }
875 else
876 {
877 angle::ReplaceSubstring(&pixelSource,
878 std::string(PIXEL_MAIN_PARAMETERS_STUB_STRING),
879 "PS_INPUT input, float vFace : VFACE");
880 }
881 }
882 else
883 {
884 angle::ReplaceSubstring(&pixelSource, std::string(PIXEL_MAIN_PARAMETERS_STUB_STRING),
885 "PS_INPUT input");
886 }
887
888 angle::ReplaceSubstring(&pixelSource, std::string(MAIN_PROLOGUE_STUB_STRING),
889 pixelPrologue.str());
890 pixelStream << pixelSource;
891 }
892
893 (*shaderHLSL)[gl::ShaderType::Vertex] = vertexStream.str();
894 (*shaderHLSL)[gl::ShaderType::Fragment] = pixelStream.str();
895 }
896
generateGeometryShaderPreamble(const VaryingPacking & varyingPacking,const BuiltinVaryingsD3D & builtinsD3D,const bool hasANGLEMultiviewEnabled,const bool selectViewInVS) const897 std::string DynamicHLSL::generateGeometryShaderPreamble(const VaryingPacking &varyingPacking,
898 const BuiltinVaryingsD3D &builtinsD3D,
899 const bool hasANGLEMultiviewEnabled,
900 const bool selectViewInVS) const
901 {
902 ASSERT(mRenderer->getMajorShaderModel() >= 4);
903
904 std::ostringstream preambleStream;
905
906 const auto &vertexBuiltins = builtinsD3D[gl::ShaderType::Vertex];
907
908 preambleStream << "struct GS_INPUT\n";
909 generateVaryingLinkHLSL(varyingPacking, vertexBuiltins, builtinsD3D.usesPointSize(),
910 preambleStream);
911 preambleStream << "\n"
912 << "struct GS_OUTPUT\n";
913 generateVaryingLinkHLSL(varyingPacking, builtinsD3D[gl::ShaderType::Geometry],
914 builtinsD3D.usesPointSize(), preambleStream);
915 preambleStream
916 << "\n"
917 << "void copyVertex(inout GS_OUTPUT output, GS_INPUT input, GS_INPUT flatinput)\n"
918 << "{\n"
919 << " output.gl_Position = input.gl_Position;\n";
920
921 if (vertexBuiltins.glPointSize.enabled)
922 {
923 preambleStream << " output.gl_PointSize = input.gl_PointSize;\n";
924 }
925
926 if (hasANGLEMultiviewEnabled)
927 {
928 preambleStream << " output.gl_ViewID_OVR = input.gl_ViewID_OVR;\n";
929 if (selectViewInVS)
930 {
931 ASSERT(builtinsD3D[gl::ShaderType::Geometry].glViewportIndex.enabled &&
932 builtinsD3D[gl::ShaderType::Geometry].glLayer.enabled);
933
934 // If the view is already selected in the VS, then we just pass the gl_ViewportIndex and
935 // gl_Layer to the output.
936 preambleStream << " output.gl_ViewportIndex = input.gl_ViewportIndex;\n"
937 << " output.gl_Layer = input.gl_Layer;\n";
938 }
939 }
940
941 const auto ®isterInfos = varyingPacking.getRegisterList();
942 for (GLuint registerIndex = 0u; registerIndex < registerInfos.size(); ++registerIndex)
943 {
944 const PackedVaryingRegister &varyingRegister = registerInfos[registerIndex];
945 preambleStream << " output.v" << registerIndex << " = ";
946 if (varyingRegister.packedVarying->interpolation == sh::INTERPOLATION_FLAT)
947 {
948 preambleStream << "flat";
949 }
950 preambleStream << "input.v" << registerIndex << "; \n";
951 }
952
953 if (vertexBuiltins.glFragCoord.enabled)
954 {
955 preambleStream << " output.gl_FragCoord = input.gl_FragCoord;\n";
956 }
957
958 // Only write the dx_Position if we aren't using point sprites
959 preambleStream << "#ifndef ANGLE_POINT_SPRITE_SHADER\n"
960 << " output.dx_Position = input.dx_Position;\n"
961 << "#endif // ANGLE_POINT_SPRITE_SHADER\n"
962 << "}\n";
963
964 if (hasANGLEMultiviewEnabled && !selectViewInVS)
965 {
966 ASSERT(builtinsD3D[gl::ShaderType::Geometry].glViewportIndex.enabled &&
967 builtinsD3D[gl::ShaderType::Geometry].glLayer.enabled);
968
969 // According to the HLSL reference, using SV_RenderTargetArrayIndex is only valid if the
970 // render target is an array resource. Because of this we do not write to gl_Layer if we are
971 // taking the side-by-side code path. We still select the viewport index in the layered code
972 // path as that is always valid. See:
973 // https://msdn.microsoft.com/en-us/library/windows/desktop/bb509647(v=vs.85).aspx
974 preambleStream << "\n"
975 << "void selectView(inout GS_OUTPUT output, GS_INPUT input)\n"
976 << "{\n"
977 << " if (multiviewSelectViewportIndex)\n"
978 << " {\n"
979 << " output.gl_ViewportIndex = input.gl_ViewID_OVR;\n"
980 << " } else {\n"
981 << " output.gl_ViewportIndex = 0;\n"
982 << " output.gl_Layer = input.gl_ViewID_OVR;\n"
983 << " }\n"
984 << "}\n";
985 }
986
987 return preambleStream.str();
988 }
989
generateGeometryShaderHLSL(const gl::Caps & caps,gl::PrimitiveMode primitiveType,const gl::ProgramState & programData,const bool useViewScale,const bool hasANGLEMultiviewEnabled,const bool selectViewInVS,const bool pointSpriteEmulation,const std::string & preambleString) const990 std::string DynamicHLSL::generateGeometryShaderHLSL(const gl::Caps &caps,
991 gl::PrimitiveMode primitiveType,
992 const gl::ProgramState &programData,
993 const bool useViewScale,
994 const bool hasANGLEMultiviewEnabled,
995 const bool selectViewInVS,
996 const bool pointSpriteEmulation,
997 const std::string &preambleString) const
998 {
999 ASSERT(mRenderer->getMajorShaderModel() >= 4);
1000
1001 std::stringstream shaderStream;
1002
1003 const bool pointSprites = (primitiveType == gl::PrimitiveMode::Points) && pointSpriteEmulation;
1004 const bool usesPointCoord = preambleString.find("gl_PointCoord") != std::string::npos;
1005
1006 const char *inputPT = nullptr;
1007 const char *outputPT = nullptr;
1008 int inputSize = 0;
1009 int maxVertexOutput = 0;
1010
1011 switch (primitiveType)
1012 {
1013 case gl::PrimitiveMode::Points:
1014 inputPT = "point";
1015 inputSize = 1;
1016
1017 if (pointSprites)
1018 {
1019 outputPT = "Triangle";
1020 maxVertexOutput = 4;
1021 }
1022 else
1023 {
1024 outputPT = "Point";
1025 maxVertexOutput = 1;
1026 }
1027
1028 break;
1029
1030 case gl::PrimitiveMode::Lines:
1031 case gl::PrimitiveMode::LineStrip:
1032 case gl::PrimitiveMode::LineLoop:
1033 inputPT = "line";
1034 outputPT = "Line";
1035 inputSize = 2;
1036 maxVertexOutput = 2;
1037 break;
1038
1039 case gl::PrimitiveMode::Triangles:
1040 case gl::PrimitiveMode::TriangleStrip:
1041 case gl::PrimitiveMode::TriangleFan:
1042 inputPT = "triangle";
1043 outputPT = "Triangle";
1044 inputSize = 3;
1045 maxVertexOutput = 3;
1046 break;
1047
1048 default:
1049 UNREACHABLE();
1050 break;
1051 }
1052
1053 if (pointSprites || hasANGLEMultiviewEnabled)
1054 {
1055 shaderStream << "cbuffer DriverConstants : register(b0)\n"
1056 "{\n";
1057
1058 if (pointSprites)
1059 {
1060 shaderStream << " float4 dx_ViewCoords : packoffset(c1);\n";
1061 if (useViewScale)
1062 {
1063 shaderStream << " float2 dx_ViewScale : packoffset(c3);\n";
1064 }
1065 }
1066
1067 if (hasANGLEMultiviewEnabled)
1068 {
1069 // We have to add a value which we can use to keep track of which multi-view code path
1070 // is to be selected in the GS.
1071 shaderStream << " float multiviewSelectViewportIndex : packoffset(c3.z);\n";
1072 }
1073
1074 shaderStream << "};\n\n";
1075 }
1076
1077 if (pointSprites)
1078 {
1079 shaderStream << "#define ANGLE_POINT_SPRITE_SHADER\n"
1080 "\n"
1081 "static float2 pointSpriteCorners[] = \n"
1082 "{\n"
1083 " float2( 0.5f, -0.5f),\n"
1084 " float2( 0.5f, 0.5f),\n"
1085 " float2(-0.5f, -0.5f),\n"
1086 " float2(-0.5f, 0.5f)\n"
1087 "};\n"
1088 "\n"
1089 "static float2 pointSpriteTexcoords[] = \n"
1090 "{\n"
1091 " float2(1.0f, 1.0f),\n"
1092 " float2(1.0f, 0.0f),\n"
1093 " float2(0.0f, 1.0f),\n"
1094 " float2(0.0f, 0.0f)\n"
1095 "};\n"
1096 "\n"
1097 "static float minPointSize = "
1098 << static_cast<int>(caps.minAliasedPointSize)
1099 << ".0f;\n"
1100 "static float maxPointSize = "
1101 << static_cast<int>(caps.maxAliasedPointSize) << ".0f;\n"
1102 << "\n";
1103 }
1104
1105 shaderStream << preambleString << "\n"
1106 << "[maxvertexcount(" << maxVertexOutput << ")]\n"
1107 << "void main(" << inputPT << " GS_INPUT input[" << inputSize << "], ";
1108
1109 if (primitiveType == gl::PrimitiveMode::TriangleStrip)
1110 {
1111 shaderStream << "uint primitiveID : SV_PrimitiveID, ";
1112 }
1113
1114 shaderStream << " inout " << outputPT << "Stream<GS_OUTPUT> outStream)\n"
1115 << "{\n"
1116 << " GS_OUTPUT output = (GS_OUTPUT)0;\n";
1117
1118 if (primitiveType == gl::PrimitiveMode::TriangleStrip)
1119 {
1120 shaderStream << " uint lastVertexIndex = (primitiveID % 2 == 0 ? 2 : 1);\n";
1121 }
1122 else
1123 {
1124 shaderStream << " uint lastVertexIndex = " << (inputSize - 1) << ";\n";
1125 }
1126
1127 for (int vertexIndex = 0; vertexIndex < inputSize; ++vertexIndex)
1128 {
1129 shaderStream << " copyVertex(output, input[" << vertexIndex
1130 << "], input[lastVertexIndex]);\n";
1131 if (hasANGLEMultiviewEnabled && !selectViewInVS)
1132 {
1133 shaderStream << " selectView(output, input[" << vertexIndex << "]);\n";
1134 }
1135 if (!pointSprites)
1136 {
1137 ASSERT(inputSize == maxVertexOutput);
1138 shaderStream << " outStream.Append(output);\n";
1139 }
1140 }
1141
1142 if (pointSprites)
1143 {
1144 shaderStream << "\n"
1145 " float4 dx_Position = input[0].dx_Position;\n"
1146 " float gl_PointSize = clamp(input[0].gl_PointSize, minPointSize, "
1147 "maxPointSize);\n"
1148 " float2 viewportScale = float2(1.0f / dx_ViewCoords.x, 1.0f / "
1149 "dx_ViewCoords.y) * dx_Position.w;\n";
1150
1151 for (int corner = 0; corner < 4; corner++)
1152 {
1153 if (useViewScale)
1154 {
1155 shaderStream << " \n"
1156 " output.dx_Position = dx_Position + float4(1.0f, "
1157 "-dx_ViewScale.y, 1.0f, 1.0f)"
1158 " * float4(pointSpriteCorners["
1159 << corner << "] * viewportScale * gl_PointSize, 0.0f, 0.0f);\n";
1160 }
1161 else
1162 {
1163 shaderStream << "\n"
1164 " output.dx_Position = dx_Position + float4(pointSpriteCorners["
1165 << corner << "] * viewportScale * gl_PointSize, 0.0f, 0.0f);\n";
1166 }
1167
1168 if (usesPointCoord)
1169 {
1170 shaderStream << " output.gl_PointCoord = pointSpriteTexcoords[" << corner
1171 << "];\n";
1172 }
1173
1174 shaderStream << " outStream.Append(output);\n";
1175 }
1176 }
1177
1178 shaderStream << " \n"
1179 " outStream.RestartStrip();\n"
1180 "}\n";
1181
1182 return shaderStream.str();
1183 }
1184
1185 // static
GenerateAttributeConversionHLSL(angle::FormatID vertexFormatID,const sh::ShaderVariable & shaderAttrib,std::ostringstream & outStream)1186 void DynamicHLSL::GenerateAttributeConversionHLSL(angle::FormatID vertexFormatID,
1187 const sh::ShaderVariable &shaderAttrib,
1188 std::ostringstream &outStream)
1189 {
1190 // Matrix
1191 if (IsMatrixType(shaderAttrib.type))
1192 {
1193 outStream << "transpose(input." << DecorateVariable(shaderAttrib.name) << ")";
1194 return;
1195 }
1196
1197 GLenum shaderComponentType = VariableComponentType(shaderAttrib.type);
1198 int shaderComponentCount = VariableComponentCount(shaderAttrib.type);
1199 const gl::VertexFormat &vertexFormat = gl::GetVertexFormatFromID(vertexFormatID);
1200
1201 // Perform integer to float conversion (if necessary)
1202 if (shaderComponentType == GL_FLOAT && vertexFormat.type != GL_FLOAT)
1203 {
1204 // TODO: normalization for 32-bit integer formats
1205 ASSERT(!vertexFormat.normalized && !vertexFormat.pureInteger);
1206 outStream << "float" << shaderComponentCount << "(input."
1207 << DecorateVariable(shaderAttrib.name) << ")";
1208 return;
1209 }
1210
1211 // No conversion necessary
1212 outStream << "input." << DecorateVariable(shaderAttrib.name);
1213 }
1214
getPixelShaderOutputKey(const gl::State & data,const gl::ProgramState & programData,const ProgramD3DMetadata & metadata,std::vector<PixelShaderOutputVariable> * outPixelShaderKey)1215 void DynamicHLSL::getPixelShaderOutputKey(const gl::State &data,
1216 const gl::ProgramState &programData,
1217 const ProgramD3DMetadata &metadata,
1218 std::vector<PixelShaderOutputVariable> *outPixelShaderKey)
1219 {
1220 // Two cases when writing to gl_FragColor and using ESSL 1.0:
1221 // - with a 3.0 context, the output color is copied to channel 0
1222 // - with a 2.0 context, the output color is broadcast to all channels
1223 bool broadcast = metadata.usesBroadcast(data);
1224 const unsigned int numRenderTargets =
1225 (broadcast || metadata.usesMultipleFragmentOuts()
1226 ? static_cast<unsigned int>(data.getCaps().maxDrawBuffers)
1227 : 1);
1228
1229 if (!metadata.usesCustomOutVars())
1230 {
1231 for (unsigned int renderTargetIndex = 0; renderTargetIndex < numRenderTargets;
1232 renderTargetIndex++)
1233 {
1234 PixelShaderOutputVariable outputKeyVariable;
1235 outputKeyVariable.type = GL_FLOAT_VEC4;
1236 outputKeyVariable.name = "gl_Color" + Str(renderTargetIndex);
1237 outputKeyVariable.source =
1238 broadcast ? "gl_Color[0]" : "gl_Color[" + Str(renderTargetIndex) + "]";
1239 outputKeyVariable.outputLocation = renderTargetIndex;
1240
1241 outPixelShaderKey->push_back(outputKeyVariable);
1242 }
1243
1244 if (metadata.usesSecondaryColor())
1245 {
1246 for (unsigned int secondaryIndex = 0;
1247 secondaryIndex < data.getExtensions().maxDualSourceDrawBuffers; secondaryIndex++)
1248 {
1249 PixelShaderOutputVariable outputKeyVariable;
1250 outputKeyVariable.type = GL_FLOAT_VEC4;
1251 outputKeyVariable.name = "gl_SecondaryColor" + Str(secondaryIndex);
1252 outputKeyVariable.source = "gl_SecondaryColor[" + Str(secondaryIndex) + "]";
1253 outputKeyVariable.outputLocation = secondaryIndex;
1254 outputKeyVariable.outputIndex = 1;
1255
1256 outPixelShaderKey->push_back(outputKeyVariable);
1257 }
1258 }
1259 }
1260 else
1261 {
1262 const ShaderD3D *fragmentShader = metadata.getFragmentShader();
1263
1264 if (!fragmentShader)
1265 {
1266 return;
1267 }
1268
1269 const auto &shaderOutputVars = fragmentShader->getState().getActiveOutputVariables();
1270
1271 for (size_t outputLocationIndex = 0u;
1272 outputLocationIndex < programData.getOutputLocations().size(); ++outputLocationIndex)
1273 {
1274 const VariableLocation &outputLocation =
1275 programData.getOutputLocations().at(outputLocationIndex);
1276 if (!outputLocation.used())
1277 {
1278 continue;
1279 }
1280 const sh::ShaderVariable &outputVariable = shaderOutputVars[outputLocation.index];
1281 const std::string &variableName = "out_" + outputVariable.name;
1282
1283 // Fragment outputs can't be arrays of arrays. ESSL 3.10 section 4.3.6.
1284 const std::string &elementString =
1285 (outputVariable.isArray() ? Str(outputLocation.arrayIndex) : "");
1286
1287 ASSERT(outputVariable.active);
1288
1289 PixelShaderOutputVariable outputKeyVariable;
1290 outputKeyVariable.type = outputVariable.type;
1291 outputKeyVariable.name = variableName + elementString;
1292 outputKeyVariable.source =
1293 variableName +
1294 (outputVariable.isArray() ? ArrayString(outputLocation.arrayIndex) : "");
1295 outputKeyVariable.outputLocation = outputLocationIndex;
1296
1297 outPixelShaderKey->push_back(outputKeyVariable);
1298 }
1299
1300 // Now generate any secondary outputs...
1301 for (size_t outputLocationIndex = 0u;
1302 outputLocationIndex < programData.getSecondaryOutputLocations().size();
1303 ++outputLocationIndex)
1304 {
1305 const VariableLocation &outputLocation =
1306 programData.getSecondaryOutputLocations().at(outputLocationIndex);
1307 if (!outputLocation.used())
1308 {
1309 continue;
1310 }
1311 const sh::ShaderVariable &outputVariable = shaderOutputVars[outputLocation.index];
1312 const std::string &variableName = "out_" + outputVariable.name;
1313
1314 // Fragment outputs can't be arrays of arrays. ESSL 3.10 section 4.3.6.
1315 const std::string &elementString =
1316 (outputVariable.isArray() ? Str(outputLocation.arrayIndex) : "");
1317
1318 ASSERT(outputVariable.active);
1319
1320 PixelShaderOutputVariable outputKeyVariable;
1321 outputKeyVariable.type = outputVariable.type;
1322 outputKeyVariable.name = variableName + elementString;
1323 outputKeyVariable.source =
1324 variableName +
1325 (outputVariable.isArray() ? ArrayString(outputLocation.arrayIndex) : "");
1326 outputKeyVariable.outputLocation = outputLocationIndex;
1327 outputKeyVariable.outputIndex = 1;
1328
1329 outPixelShaderKey->push_back(outputKeyVariable);
1330 }
1331 }
1332 }
1333
1334 // BuiltinVarying Implementation.
BuiltinVarying()1335 BuiltinVarying::BuiltinVarying() : enabled(false), index(0), systemValue(false) {}
1336
str() const1337 std::string BuiltinVarying::str() const
1338 {
1339 return (systemValue ? semantic : (semantic + Str(index)));
1340 }
1341
enableSystem(const std::string & systemValueSemantic)1342 void BuiltinVarying::enableSystem(const std::string &systemValueSemantic)
1343 {
1344 enabled = true;
1345 semantic = systemValueSemantic;
1346 systemValue = true;
1347 }
1348
enable(const std::string & semanticVal,unsigned int indexVal)1349 void BuiltinVarying::enable(const std::string &semanticVal, unsigned int indexVal)
1350 {
1351 enabled = true;
1352 semantic = semanticVal;
1353 index = indexVal;
1354 }
1355
1356 // BuiltinVaryingsD3D Implementation.
BuiltinVaryingsD3D(const ProgramD3DMetadata & metadata,const VaryingPacking & packing)1357 BuiltinVaryingsD3D::BuiltinVaryingsD3D(const ProgramD3DMetadata &metadata,
1358 const VaryingPacking &packing)
1359 {
1360 updateBuiltins(gl::ShaderType::Vertex, metadata, packing);
1361 updateBuiltins(gl::ShaderType::Fragment, metadata, packing);
1362 int shaderModel = metadata.getRendererMajorShaderModel();
1363 if (shaderModel >= 4)
1364 {
1365 updateBuiltins(gl::ShaderType::Geometry, metadata, packing);
1366 }
1367 // In shader model >= 4, some builtins need to be the same in vertex and pixel shaders - input
1368 // struct needs to be a prefix of output struct.
1369 ASSERT(shaderModel < 4 || mBuiltinInfo[gl::ShaderType::Vertex].glPosition.enabled ==
1370 mBuiltinInfo[gl::ShaderType::Fragment].glPosition.enabled);
1371 ASSERT(shaderModel < 4 || mBuiltinInfo[gl::ShaderType::Vertex].glFragCoord.enabled ==
1372 mBuiltinInfo[gl::ShaderType::Fragment].glFragCoord.enabled);
1373 ASSERT(shaderModel < 4 || mBuiltinInfo[gl::ShaderType::Vertex].glPointCoord.enabled ==
1374 mBuiltinInfo[gl::ShaderType::Fragment].glPointCoord.enabled);
1375 ASSERT(shaderModel < 4 || mBuiltinInfo[gl::ShaderType::Vertex].glPointSize.enabled ==
1376 mBuiltinInfo[gl::ShaderType::Fragment].glPointSize.enabled);
1377 ASSERT(shaderModel < 4 || mBuiltinInfo[gl::ShaderType::Vertex].glViewIDOVR.enabled ==
1378 mBuiltinInfo[gl::ShaderType::Fragment].glViewIDOVR.enabled);
1379 }
1380
1381 BuiltinVaryingsD3D::~BuiltinVaryingsD3D() = default;
1382
updateBuiltins(gl::ShaderType shaderType,const ProgramD3DMetadata & metadata,const VaryingPacking & packing)1383 void BuiltinVaryingsD3D::updateBuiltins(gl::ShaderType shaderType,
1384 const ProgramD3DMetadata &metadata,
1385 const VaryingPacking &packing)
1386 {
1387 const std::string &userSemantic = GetVaryingSemantic(metadata.getRendererMajorShaderModel(),
1388 metadata.usesSystemValuePointSize());
1389
1390 // Note that when enabling builtins only for specific shader stages in shader model >= 4, the
1391 // code needs to ensure that the input struct of the shader stage is a prefix of the output
1392 // struct of the previous stage.
1393
1394 unsigned int reservedSemanticIndex = packing.getMaxSemanticIndex();
1395
1396 BuiltinInfo *builtins = &mBuiltinInfo[shaderType];
1397
1398 if (metadata.getRendererMajorShaderModel() >= 4)
1399 {
1400 builtins->dxPosition.enableSystem("SV_Position");
1401 }
1402 else if (shaderType == gl::ShaderType::Fragment)
1403 {
1404 builtins->dxPosition.enableSystem("VPOS");
1405 }
1406 else
1407 {
1408 builtins->dxPosition.enableSystem("POSITION");
1409 }
1410
1411 if (metadata.usesTransformFeedbackGLPosition())
1412 {
1413 builtins->glPosition.enable(userSemantic, reservedSemanticIndex++);
1414 }
1415
1416 if (metadata.usesFragCoord())
1417 {
1418 builtins->glFragCoord.enable(userSemantic, reservedSemanticIndex++);
1419 }
1420
1421 if (shaderType == gl::ShaderType::Vertex ? metadata.addsPointCoordToVertexShader()
1422 : metadata.usesPointCoord())
1423 {
1424 // SM3 reserves the TEXCOORD semantic for point sprite texcoords (gl_PointCoord)
1425 // In D3D11 we manually compute gl_PointCoord in the GS.
1426 if (metadata.getRendererMajorShaderModel() >= 4)
1427 {
1428 builtins->glPointCoord.enable(userSemantic, reservedSemanticIndex++);
1429 }
1430 else
1431 {
1432 builtins->glPointCoord.enable("TEXCOORD", 0);
1433 }
1434 }
1435
1436 if (metadata.hasANGLEMultiviewEnabled())
1437 {
1438 // Although it is possible to compute gl_ViewID_OVR from the value of
1439 // SV_ViewportArrayIndex or SV_RenderTargetArrayIndex and the multi-view state in the
1440 // driver constant buffer, it is easier and cleaner to always pass it as a varying.
1441 builtins->glViewIDOVR.enable(userSemantic, reservedSemanticIndex++);
1442
1443 if (shaderType == gl::ShaderType::Vertex)
1444 {
1445 if (metadata.canSelectViewInVertexShader())
1446 {
1447 builtins->glViewportIndex.enableSystem("SV_ViewportArrayIndex");
1448 builtins->glLayer.enableSystem("SV_RenderTargetArrayIndex");
1449 }
1450 }
1451
1452 if (shaderType == gl::ShaderType::Geometry)
1453 {
1454 // gl_Layer and gl_ViewportIndex are necessary so that we can write to either based on
1455 // the multiview state in the driver constant buffer.
1456 builtins->glViewportIndex.enableSystem("SV_ViewportArrayIndex");
1457 builtins->glLayer.enableSystem("SV_RenderTargetArrayIndex");
1458 }
1459 }
1460
1461 // Special case: do not include PSIZE semantic in HLSL 3 pixel shaders
1462 if (metadata.usesSystemValuePointSize() &&
1463 (shaderType != gl::ShaderType::Fragment || metadata.getRendererMajorShaderModel() >= 4))
1464 {
1465 builtins->glPointSize.enableSystem("PSIZE");
1466 }
1467 }
1468
1469 } // namespace rx
1470