1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
| import * as vscode from 'vscode'; import { CocosShaderLanguageProvider } from './languageProvider'; import { CocosShaderDiagnosticsProvider } from './diagnosticsProvider'; import { CocosShaderPreviewProvider } from './previewProvider';
export function activate(context: vscode.ExtensionContext) { console.log('🚀 Cocos Shader扩展已激�?); // 注册语言服务提供�? const languageProvider = new CocosShaderLanguageProvider(); context.subscriptions.push( vscode.languages.registerCompletionItemProvider( { language: 'cocos-shader' }, languageProvider, '.', '_', ':' ) ); // 注册诊断提供�? const diagnosticsProvider = new CocosShaderDiagnosticsProvider(); context.subscriptions.push(diagnosticsProvider); // 注册预览提供�? const previewProvider = new CocosShaderPreviewProvider(context); context.subscriptions.push( vscode.window.registerWebviewViewProvider( 'cocosShaderPreview', previewProvider ) ); // 注册命令 registerCommands(context); // 监听文件变化 setupFileWatchers(context); }
class CocosShaderLanguageProvider implements vscode.CompletionItemProvider { private keywords: vscode.CompletionItem[] = []; private functions: vscode.CompletionItem[] = []; private types: vscode.CompletionItem[] = []; constructor() { this.initializeCompletions(); } private initializeCompletions(): void { // GLSL关键字补�? const glslKeywords = [ 'precision', 'highp', 'mediump', 'lowp', 'in', 'out', 'inout', 'uniform', 'varying', 'attribute', 'layout', 'location', 'binding', 'if', 'else', 'for', 'while', 'do', 'break', 'continue', 'return', 'discard' ]; this.keywords = glslKeywords.map(keyword => { const item = new vscode.CompletionItem(keyword, vscode.CompletionItemKind.Keyword); item.detail = `GLSL关键字`; return item; }); // GLSL内置函数补全 const glslFunctions = [ { name: 'texture', detail: 'texture(sampler, coord)', doc: '纹理采样函数' }, { name: 'normalize', detail: 'normalize(vec)', doc: '向量归一�? }, { name: 'dot', detail: 'dot(vec1, vec2)', doc: '向量点积' }, { name: 'cross', detail: 'cross(vec1, vec2)', doc: '向量叉积' }, { name: 'mix', detail: 'mix(x, y, a)', doc: '线性插�? }, { name: 'step', detail: 'step(edge, x)', doc: '阶跃函数' }, { name: 'smoothstep', detail: 'smoothstep(edge0, edge1, x)', doc: '平滑阶跃函数' }, { name: 'clamp', detail: 'clamp(x, minVal, maxVal)', doc: '值限制函�? }, { name: 'pow', detail: 'pow(x, y)', doc: '幂函�? }, { name: 'sin', detail: 'sin(angle)', doc: '正弦函数' }, { name: 'cos', detail: 'cos(angle)', doc: '余弦函数' } ]; this.functions = glslFunctions.map(func => { const item = new vscode.CompletionItem(func.name, vscode.CompletionItemKind.Function); item.detail = func.detail; item.documentation = new vscode.MarkdownString(func.doc); item.insertText = new vscode.SnippetString(`${func.name}($1)`); return item; }); // GLSL类型补全 const glslTypes = [ 'void', 'bool', 'int', 'uint', 'float', 'vec2', 'vec3', 'vec4', 'bvec2', 'bvec3', 'bvec4', 'ivec2', 'ivec3', 'ivec4', 'uvec2', 'uvec3', 'uvec4', 'mat2', 'mat3', 'mat4', 'sampler2D', 'samplerCube', 'sampler2DArray' ]; this.types = glslTypes.map(type => { const item = new vscode.CompletionItem(type, vscode.CompletionItemKind.Class); item.detail = `GLSL数据类型`; return item; }); } public provideCompletionItems( document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext ): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { const line = document.lineAt(position); const linePrefix = line.text.substr(0, position.character); // 检查是否在CCEffect块中 if (this.isInCCEffectBlock(document, position)) { return this.provideCCEffectCompletions(linePrefix); } // 检查是否在CCProgram块中 if (this.isInCCProgramBlock(document, position)) { return this.provideGLSLCompletions(linePrefix); } return []; } private isInCCEffectBlock(document: vscode.TextDocument, position: vscode.Position): boolean { // 检查是否在CCEffect %{ ... }%块中 const text = document.getText(new vscode.Range(0, 0, position.line, position.character)); const ccEffectStart = text.lastIndexOf('CCEffect %{'); const ccEffectEnd = text.lastIndexOf('}%'); return ccEffectStart > ccEffectEnd; } private isInCCProgramBlock(document: vscode.TextDocument, position: vscode.Position): boolean { // 检查是否在CCProgram %{ ... }%块中 const text = document.getText(new vscode.Range(0, 0, position.line, position.character)); const ccProgramStart = text.lastIndexOf('CCProgram'); const ccProgramEnd = text.lastIndexOf('}%'); return ccProgramStart > ccProgramEnd; } private provideCCEffectCompletions(linePrefix: string): vscode.CompletionItem[] { // CCEffect YAML配置补全 const ccEffectItems = [ this.createYamlCompletionItem('techniques', 'techniques:\n- name: ${1:technique-name}'), this.createYamlCompletionItem('passes', 'passes:\n- vert: ${1:vs}:vert\n frag: ${2:fs}:frag'), this.createYamlCompletionItem('properties', 'properties:\n ${1:property}: { value: ${2:value} }'), this.createYamlCompletionItem('rasterizerState', 'rasterizerState:\n cullMode: ${1:back}'), this.createYamlCompletionItem('depthStencilState', 'depthStencilState:\n depthTest: ${1:true}\n depthWrite: ${2:true}'), this.createYamlCompletionItem('blendState', 'blendState:\n targets:\n - blend: ${1:true}') ]; return ccEffectItems; } private provideGLSLCompletions(linePrefix: string): vscode.CompletionItem[] { return [...this.keywords, ...this.functions, ...this.types]; } private createYamlCompletionItem(label: string, snippet: string): vscode.CompletionItem { const item = new vscode.CompletionItem(label, vscode.CompletionItemKind.Property); item.insertText = new vscode.SnippetString(snippet); item.detail = 'CCEffect配置'; return item; } }
class CocosShaderDiagnosticsProvider { private diagnosticCollection: vscode.DiagnosticCollection; constructor() { this.diagnosticCollection = vscode.languages.createDiagnosticCollection('cocos-shader'); // 监听文档变化 vscode.workspace.onDidSaveTextDocument(this.validateDocument, this); vscode.workspace.onDidOpenTextDocument(this.validateDocument, this); vscode.workspace.onDidChangeTextDocument(event => { this.validateDocument(event.document); }); } private validateDocument(document: vscode.TextDocument): void { if (document.languageId !== 'cocos-shader') { return; } const diagnostics: vscode.Diagnostic[] = []; const text = document.getText(); // 检查常见错�? this.checkSyntaxErrors(document, text, diagnostics); this.checkBestPractices(document, text, diagnostics); this.diagnosticCollection.set(document.uri, diagnostics); } private checkSyntaxErrors(document: vscode.TextDocument, text: string, diagnostics: vscode.Diagnostic[]): void { // 检查CCEffect块语�? const ccEffectMatches = text.matchAll(/CCEffect\s*%\{[\s\S]*?\}%/g); for (const match of ccEffectMatches) { // 验证YAML语法 const yamlContent = match[0].slice(match[0].indexOf('%{') + 2, -2); try { // 这里可以使用yaml解析库验证语�? } catch (error) { const range = this.getMatchRange(document, match); diagnostics.push(new vscode.Diagnostic( range, `CCEffect YAML语法错误: ${error.message}`, vscode.DiagnosticSeverity.Error )); } } // 检查CCProgram块语�? const ccProgramMatches = text.matchAll(/CCProgram\s+(\w+)\s*%\{[\s\S]*?\}%/g); for (const match of ccProgramMatches) { this.validateGLSLSyntax(document, match, diagnostics); } } private checkBestPractices(document: vscode.TextDocument, text: string, diagnostics: vscode.Diagnostic[]): void { // 检查性能最佳实�? const lines = text.split('\n'); lines.forEach((line, index) => { const trimmedLine = line.trim(); // 检查精度声�? if (trimmedLine.includes('float') && !text.includes('precision')) { const range = new vscode.Range(index, 0, index, line.length); diagnostics.push(new vscode.Diagnostic( range, '建议在着色器开头声明精度:precision mediump float;', vscode.DiagnosticSeverity.Warning )); } // 检查discard使用 if (trimmedLine.includes('discard')) { const range = new vscode.Range(index, line.indexOf('discard'), index, line.indexOf('discard') + 7); diagnostics.push(new vscode.Diagnostic( range, '过度使用discard可能影响性能,特别是在移动设备上', vscode.DiagnosticSeverity.Information )); } // 检查复杂数学函�? const expensiveFunctions = ['pow', 'sin', 'cos', 'tan', 'exp', 'log']; expensiveFunctions.forEach(func => { if (trimmedLine.includes(func + '(')) { const range = new vscode.Range(index, line.indexOf(func), index, line.indexOf(func) + func.length); diagnostics.push(new vscode.Diagnostic( range, `${func}是昂贵的数学函数,考虑使用查找表或近似算法`, vscode.DiagnosticSeverity.Information )); } }); }); } private validateGLSLSyntax(document: vscode.TextDocument, match: RegExpMatchArray, diagnostics: vscode.Diagnostic[]): void { // 简化的GLSL语法验证 const glslContent = match[0]; // 检查括号匹�? let braceCount = 0; let parenCount = 0; for (let i = 0; i < glslContent.length; i++) { switch (glslContent[i]) { case '{': braceCount++; break; case '}': braceCount--; break; case '(': parenCount++; break; case ')': parenCount--; break; } } if (braceCount !== 0 || parenCount !== 0) { const range = this.getMatchRange(document, match); diagnostics.push(new vscode.Diagnostic( range, '括号不匹�?, vscode.DiagnosticSeverity.Error )); } } private getMatchRange(document: vscode.TextDocument, match: RegExpMatchArray): vscode.Range { const text = document.getText(); const startIndex = match.index || 0; const endIndex = startIndex + match[0].length; const startPos = document.positionAt(startIndex); const endPos = document.positionAt(endIndex); return new vscode.Range(startPos, endPos); } public dispose(): void { this.diagnosticCollection.dispose(); } }
|