text
stringlengths
1
1.05M
; A164315: Number of binary strings of length n with no substrings equal to 000 or 011. ; 1,2,4,6,9,13,18,25,34,46,62,83,111,148,197,262,348,462,613,813,1078,1429,1894,2510,3326,4407,5839,7736,10249,13578,17988,23830,31569,41821,55402,73393,97226,128798,170622,226027,299423,396652,525453,696078,922108,1221534,1618189,2143645,2839726,3761837,4983374,6601566,8745214,11584943,15346783,20330160,26931729,35676946,47261892,62608678,82938841,109870573,145547522,192809417,255418098,338356942,448227518,593775043,786584463,1042002564,1380359509,1828587030,2422362076,3208946542,4250949109,5631308621,7459895654,9882257733,13091204278,17342153390,22973462014,30433357671,40315615407,53406819688,70748973081,93722435098,124155792772,164471408182,217878227873,288627200957,382349636058,506505428833,670976837018,888855064894,1177482265854,1559831901915,2066337330751,2737314167772,3626169232669,4803651498526,6363483400444,8429820731198,11167134898973,14793304131645,19596955630174,25960439030621,34390259761822,45557394660798,60350698792446,79947654422623,105908093453247,140298353215072,185855747875873,246206446668322,326154101090948,432062194544198,572360547759273,758216295635149,1004422742303474,1330576843394425,1762639037938626,2334999585697902,3093215881333054,4097638623636531,5428215467030959,7190854504969588 add $0,6 cal $0,134816 ; Padovan's spiral numbers. mov $1,$0 sub $1,3
; timer interrupt is apparently not invoked anyway Timer:: reti
; char *_memstrcpy_(void *p, char *s, size_t n) SECTION code_string PUBLIC __memstrcpy_ EXTERN asm__memstrcpy __memstrcpy_: pop af pop de pop hl pop bc push bc push hl push de push af jp asm__memstrcpy
; ASM source file created by SevenuP v1.20 ; SevenuP (C) Copyright 2002-2006 by Jaime Tejedor Gomez, aka Metalbrain ;GRAPHIC DATA: ;Pixel Size: ( 24, 32) ;Char Size: ( 3, 4) ;Sort Priorities: X char, Char line, Y char ;Data Outputted: Gfx ;Interleave: Sprite ;Mask: No barbaro_idle_espada: DEFB 0, 0, 0, 24, 0, 0, 24, 0 DEFB 0, 12, 7,192, 12, 8, 32, 12 DEFB 16, 16, 6, 34,144, 6, 3,192 DEFB 6,115,192, 3,121,128, 3,124 DEFB 16, 3,110,104, 1,135, 96, 13 DEFB 131, 72, 29,164, 16, 28,207, 8 DEFB 14,144, 80, 5, 57,224, 0, 89 DEFB 192, 0,224, 0, 0, 0, 0, 0 DEFB 0,160, 1,193, 80, 3,226,168 DEFB 7,192, 80, 7,128, 0, 0, 64 DEFB 80, 3,128, 0, 0, 64, 64, 0 DEFB 192,128, 3,193, 80, 15,226,168
%include "options.asm" %include "lz0a_const.asm" %include "data_struct2.asm" %include "bitbuf2.asm" %include "huffman.asm" %include "igzip_compare_types.asm" %include "reg_sizes.asm" %include "stdmac.asm" extern rfc1951_lookup_table _len_to_code_offset equ 0 %define LAST_BYTES_COUNT 3 ; Bytes to prevent reading out of array bounds %define LA_STATELESS 280 ; Max number of bytes read in loop2 rounded up to 8 byte boundary %define LIT_LEN 286 %define DIST_LEN 30 %define HIST_ELEM_SIZE 8 %ifdef DEBUG %macro MARK 1 global %1 %1: %endm %else %macro MARK 1 %endm %endif ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %define file_start rdi %define file_length rsi %define histogram rdx %define rfc_lookup r9 %define f_i r10 %define curr_data rax %define tmp2 rcx %define dist rbx %define dist_code2 rbx %define dist2 r12 %define dist_code r12 %define len rbp %define len_code rbp %define hash3 rbp %define curr_data2 r8 %define len2 r8 %define tmp4 r8 %define tmp1 r11 %define tmp3 r13 %define hash r14 %define hash2 r15 %define xtmp0 xmm0 %define xtmp1 xmm1 %define xdata xmm2 %define ytmp0 ymm0 %define ytmp1 ymm1 %if(ARCH == 01) %define vtmp0 xtmp0 %define vtmp1 xtmp1 %define V_LENGTH 16 %else %define vtmp0 ytmp0 %define vtmp1 ytmp1 %define V_LENGTH 32 %endif ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; _eob_count_offset equ 0 ; local variable (8 bytes) f_end_i_mem_offset equ 8 gpr_save_mem_offset equ 16 ; gpr save area (8*8 bytes) xmm_save_mem_offset equ 16 + 8*8 ; xmm save area (4*16 bytes) (16 byte aligned) stack_size equ 2*8 + 8*8 + 4*16 + 8 ;;; 8 because stack address is odd multiple of 8 after a function call and ;;; we want it aligned to 16 bytes %ifidn __OUTPUT_FORMAT__, elf64 %define arg0 rdi %define arg1 rsi %define arg2 rdx %macro FUNC_SAVE 0 %ifdef ALIGN_STACK push rbp mov rbp, rsp sub rsp, stack_size and rsp, ~15 %else sub rsp, stack_size %endif mov [rsp + gpr_save_mem_offset + 0*8], rbx mov [rsp + gpr_save_mem_offset + 1*8], rbp mov [rsp + gpr_save_mem_offset + 2*8], r12 mov [rsp + gpr_save_mem_offset + 3*8], r13 mov [rsp + gpr_save_mem_offset + 4*8], r14 mov [rsp + gpr_save_mem_offset + 5*8], r15 %endm %macro FUNC_RESTORE 0 mov rbx, [rsp + gpr_save_mem_offset + 0*8] mov rbp, [rsp + gpr_save_mem_offset + 1*8] mov r12, [rsp + gpr_save_mem_offset + 2*8] mov r13, [rsp + gpr_save_mem_offset + 3*8] mov r14, [rsp + gpr_save_mem_offset + 4*8] mov r15, [rsp + gpr_save_mem_offset + 5*8] %ifndef ALIGN_STACK add rsp, stack_size %else mov rsp, rbp pop rbp %endif %endm %endif %ifidn __OUTPUT_FORMAT__, win64 %define arg0 rcx %define arg1 rdx %define arg2 r8 %macro FUNC_SAVE 0 %ifdef ALIGN_STACK push rbp mov rbp, rsp sub rsp, stack_size and rsp, ~15 %else sub rsp, stack_size %endif mov [rsp + gpr_save_mem_offset + 0*8], rbx mov [rsp + gpr_save_mem_offset + 1*8], rsi mov [rsp + gpr_save_mem_offset + 2*8], rdi mov [rsp + gpr_save_mem_offset + 3*8], rbp mov [rsp + gpr_save_mem_offset + 4*8], r12 mov [rsp + gpr_save_mem_offset + 5*8], r13 mov [rsp + gpr_save_mem_offset + 6*8], r14 mov [rsp + gpr_save_mem_offset + 7*8], r15 %endm %macro FUNC_RESTORE 0 mov rbx, [rsp + gpr_save_mem_offset + 0*8] mov rsi, [rsp + gpr_save_mem_offset + 1*8] mov rdi, [rsp + gpr_save_mem_offset + 2*8] mov rbp, [rsp + gpr_save_mem_offset + 3*8] mov r12, [rsp + gpr_save_mem_offset + 4*8] mov r13, [rsp + gpr_save_mem_offset + 5*8] mov r14, [rsp + gpr_save_mem_offset + 6*8] mov r15, [rsp + gpr_save_mem_offset + 7*8] %ifndef ALIGN_STACK add rsp, stack_size %else mov rsp, rbp pop rbp %endif %endm %endif _lit_len_offset equ 0 _dist_offset equ (8 * LIT_LEN) _hash_offset equ (_dist_offset + 8 * DIST_LEN) %macro len_to_len_code 3 %define %%len_code %1 ; Output %define %%len %2 ; Input %define %%rfc_lookup %3 movzx %%len_code, byte [%%rfc_lookup + _len_to_code_offset + %%len] or %%len_code, 0x100 %endm ;;; Clobbers rcx and dist %macro dist_to_dist_code 2 %define %%dist_code %1 ; Output code associated with dist %define %%dist_coded %1d %define %%dist %2d ; Input dist dec %%dist mov %%dist_coded, %%dist bsr ecx, %%dist_coded dec ecx SHRX %%dist_code, %%dist_code, rcx lea %%dist_coded, [%%dist_coded + 2*ecx] cmp %%dist, 1 cmovle %%dist_coded, %%dist %endm ;;; Clobbers rcx and dist %macro dist_to_dist_code2 2 %define %%dist_code %1 ; Output code associated with dist %define %%dist_coded %1d %define %%dist %2d ; Input -(dist - 1) neg %%dist mov %%dist_coded, %%dist bsr ecx, %%dist_coded dec ecx SHRX %%dist_code, %%dist_code, rcx lea %%dist_coded, [%%dist_coded + 2*ecx] cmp %%dist, 1 cmovle %%dist_coded, %%dist %endm ; void isal_update_histogram global isal_update_histogram_ %+ ARCH isal_update_histogram_ %+ ARCH %+ : FUNC_SAVE %ifnidn file_start, arg0 mov file_start, arg0 %endif %ifnidn file_length, arg1 mov file_length, arg1 %endif %ifnidn histogram, arg2 mov histogram, arg2 %endif mov f_i, 0 cmp file_length, 0 je exit_ret ; If nothing to do then exit mov tmp1, qword [histogram + _lit_len_offset + 8*256] inc tmp1 mov [rsp + _eob_count_offset], tmp1 lea rfc_lookup, [rfc1951_lookup_table] ;; Init hash_table PXOR vtmp0, vtmp0, vtmp0 mov rcx, (IGZIP_HASH_SIZE - V_LENGTH) init_hash_table: MOVDQU [histogram + _hash_offset + 2 * rcx], vtmp0 MOVDQU [histogram + _hash_offset + 2 * (rcx + V_LENGTH / 2)], vtmp0 sub rcx, V_LENGTH jge init_hash_table sub file_length, LA_STATELESS cmp file_length, 0 jle end_loop_2 ;; Load first literal into histogram mov curr_data, [file_start + f_i] compute_hash hash, curr_data and hash %+ d, HASH_MASK mov [histogram + _hash_offset + 2 * hash], f_i %+ w and curr_data, 0xff inc qword [histogram + _lit_len_offset + HIST_ELEM_SIZE * curr_data] inc f_i ;; Setup to begin loop 2 MOVDQU xdata, [file_start + f_i] mov curr_data, [file_start + f_i] mov curr_data2, curr_data compute_hash hash, curr_data shr curr_data2, 8 compute_hash hash2, curr_data2 and hash2 %+ d, HASH_MASK and hash, HASH_MASK loop2: xor dist, dist xor dist2, dist2 xor tmp3, tmp3 lea tmp1, [file_start + f_i] MOVQ curr_data, xdata PSRLDQ xdata, 1 ;; Load possible look back distances and update hash data mov dist %+ w, f_i %+ w sub dist, 1 sub dist %+ w, word [histogram + _hash_offset + 2 * hash] mov [histogram + _hash_offset + 2 * hash], f_i %+ w add f_i, 1 mov dist2 %+ w, f_i %+ w sub dist2, 1 sub dist2 %+ w, word [histogram + _hash_offset + 2 * hash2] mov [histogram + _hash_offset + 2 * hash2], f_i %+ w ;; Start computing hashes to be used in either the next loop or ;; for updating the hash if a match is found MOVQ curr_data2, xdata MOVQ tmp2, xdata shr curr_data2, 8 compute_hash hash, curr_data2 ;; Check if look back distances are valid. Load a junk distance of 1 ;; if the look back distance is too long for speculative lookups. and dist %+ d, (D-1) neg dist and dist2 %+ d, (D-1) neg dist2 shr tmp2, 16 compute_hash hash2, tmp2 ;; Check for long len/dist matches (>7) mov len, curr_data xor len, [tmp1 + dist - 1] jz compare_loop and hash %+ d, HASH_MASK and hash2 %+ d, HASH_MASK MOVQ len2, xdata xor len2, [tmp1 + dist2] jz compare_loop2 ;; Specutively load the code for the first literal movzx tmp1, curr_data %+ b shr curr_data, 8 lea tmp3, [f_i + 1] ;; Check for len/dist match for first literal test len %+ d, 0xFFFFFFFF jz len_dist_huffman_pre ;; Store first literal inc qword [histogram + _lit_len_offset + HIST_ELEM_SIZE * tmp1] ;; Check for len/dist match for second literal test len2 %+ d, 0xFFFFFFFF jnz lit_lit_huffman len_dist_lit_huffman_pre: ;; Calculate repeat length tzcnt len2, len2 shr len2, 3 len_dist_lit_huffman: MOVQ curr_data, xdata shr curr_data, 24 compute_hash hash3, curr_data ;; Store updated hashes mov [histogram + _hash_offset + 2 * hash], tmp3 %+ w add tmp3,1 mov [histogram + _hash_offset + 2 * hash2], tmp3 %+ w add tmp3, 1 add f_i, len2 MOVDQU xdata, [file_start + f_i] mov curr_data, [file_start + f_i] mov tmp1, curr_data compute_hash hash, curr_data and hash3, HASH_MASK mov [histogram + _hash_offset + 2 * hash3], tmp3 %+ w dist_to_dist_code2 dist_code2, dist2 len_to_len_code len_code, len2, rfc_lookup shr tmp1, 8 compute_hash hash2, tmp1 inc qword [histogram + _lit_len_offset + HIST_ELEM_SIZE * len_code] inc qword [histogram + _dist_offset + HIST_ELEM_SIZE * dist_code2] and hash2 %+ d, HASH_MASK and hash, HASH_MASK cmp f_i, file_length jl loop2 jmp end_loop_2 ;; encode as dist/len len_dist_huffman_pre: tzcnt len, len shr len, 3 len_dist_huffman: mov [histogram + _hash_offset + 2 * hash], tmp3 %+ w add tmp3,1 mov [histogram + _hash_offset + 2 * hash2], tmp3 %+ w dec f_i add f_i, len MOVDQU xdata, [file_start + f_i] mov curr_data, [file_start + f_i] mov tmp1, curr_data compute_hash hash, curr_data dist_to_dist_code2 dist_code, dist len_to_len_code len_code, len, rfc_lookup shr tmp1, 8 compute_hash hash2, tmp1 inc qword [histogram + _lit_len_offset + HIST_ELEM_SIZE * len_code] inc qword [histogram + _dist_offset + HIST_ELEM_SIZE * dist_code] and hash2 %+ d, HASH_MASK and hash, HASH_MASK cmp f_i, file_length jl loop2 jmp end_loop_2 lit_lit_huffman: MOVDQU xdata, [file_start + f_i + 1] and curr_data, 0xff add f_i, 1 inc qword [histogram + _lit_len_offset + HIST_ELEM_SIZE * curr_data] cmp f_i, file_length jl loop2 end_loop_2: add file_length, LA_STATELESS - LAST_BYTES_COUNT cmp f_i, file_length jge final_bytes loop2_finish: mov curr_data %+ d, dword [file_start + f_i] compute_hash hash, curr_data and hash %+ d, HASH_MASK ;; Calculate possible distance for length/dist pair. xor dist, dist mov dist %+ w, f_i %+ w sub dist %+ w, word [histogram + _hash_offset + 2 * hash] mov [histogram + _hash_offset + 2 * hash], f_i %+ w ;; Check if look back distance is valid (the dec is to handle when dist = 0) dec dist cmp dist %+ d, (D-1) jae encode_literal_finish inc dist ;; Check if look back distance is a match lea tmp4, [file_length + LAST_BYTES_COUNT] sub tmp4, f_i lea tmp1, [file_start + f_i] mov tmp2, tmp1 sub tmp2, dist compare tmp4, tmp1, tmp2, len, tmp3 ;; Limit len to maximum value of 258 mov tmp2, 258 cmp len, 258 cmova len, tmp2 cmp len, SHORTEST_MATCH jb encode_literal_finish add f_i, len len_to_len_code len_code, len, rfc_lookup dist_to_dist_code dist_code, dist inc qword [histogram + _lit_len_offset + HIST_ELEM_SIZE * len_code] inc qword [histogram + _dist_offset + HIST_ELEM_SIZE * dist_code] cmp f_i, file_length jl loop2_finish jmp final_bytes encode_literal_finish: ;; Encode literal and curr_data %+ d, 0xFF inc qword [histogram + _lit_len_offset + HIST_ELEM_SIZE * curr_data] ;; Setup for next loop add f_i, 1 cmp f_i, file_length jl loop2_finish final_bytes: add file_length, LAST_BYTES_COUNT final_bytes_loop: cmp f_i, file_length jge end movzx curr_data, byte [file_start + f_i] inc qword [histogram + _lit_len_offset + HIST_ELEM_SIZE * curr_data] inc f_i jmp final_bytes_loop end: ;; Handle eob at end of stream mov tmp1, [rsp + _eob_count_offset] mov qword [histogram + _lit_len_offset + HIST_ELEM_SIZE * 256], tmp1 exit_ret: FUNC_RESTORE ret compare_loop: and hash %+ d, HASH_MASK and hash2 %+ d, HASH_MASK lea tmp2, [tmp1 + dist - 1] %if (COMPARE_TYPE == 1) compare250 tmp1, tmp2, len, tmp3 %elif (COMPARE_TYPE == 2) compare250_x tmp1, tmp2, len, tmp3, xtmp0, xtmp1 %elif (COMPARE_TYPE == 3) compare250_y tmp1, tmp2, len, tmp3, ytmp0, ytmp1 %else %error Unknown Compare type COMPARE_TYPE % error %endif lea tmp3, [f_i + 1] jmp len_dist_huffman compare_loop2: add tmp1, 1 lea tmp2, [tmp1 + dist2 - 1] %if (COMPARE_TYPE == 1) compare250 tmp1, tmp2, len2, tmp3 %elif (COMPARE_TYPE == 2) compare250_x tmp1, tmp2, len2, tmp3, xtmp0, xtmp1 %elif (COMPARE_TYPE == 3) compare250_y tmp1, tmp2, len2, tmp3, ytmp0, ytmp1 %else %error Unknown Compare type COMPARE_TYPE % error %endif and curr_data, 0xff inc qword [histogram + _lit_len_offset + 8 * curr_data] lea tmp3, [f_i + 1] jmp len_dist_lit_huffman section .data align 32 D_vector: dw -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF dw -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF dw -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF dw -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF, -(D + 1) & 0xFFFF
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; ReadDr1.Asm ; ; Abstract: ; ; AsmReadDr1 function ; ; Notes: ; ;------------------------------------------------------------------------------ .586p .model flat,C .code ;------------------------------------------------------------------------------ ; UINTN ; EFIAPI ; AsmReadDr1 ( ; VOID ; ); ;------------------------------------------------------------------------------ AsmReadDr1 PROC mov eax, dr1 ret AsmReadDr1 ENDP END
bits 64 default rel section .text global pal_execute_vmclear_checked pal_execute_vmclear_checked : vmclear [rdi] jbe pal_execute_vmclear_checked_failure mov rax, 0x1 ret pal_execute_vmclear_checked_failure : mov rax, 0x0 ret
## MIPS Assignment #1 ## Ch13 4.asm ## Arithmetic Expression: 3x - 5y, initialize x=1, y=2 .text .globl main main: ori $8, $0, 0x01 # initialize $8(x) to 1 ori $9, $0, 0x02 # initialize $9(y) to 2 or $6, $0, $8 # set x to $6 for temporary or $7, $0, $9 # set y to $7 for temporary sll $8, $8, 1 # 2*x by shift $8 left l add $8, $8, $6 # 2*x + x= 3x by add $6 sll $9, $9, 2 # 4*y by shift $9 left 2 add $9, $9, $7 # 4*y + y =5y by add $7 sub $10, $8, $9 # 3x - 5y then store to $10 ## End of file
; A133628: a(1)=1, a(n) = a(n-1) + (p-1)*p^(n/2-1) if n is even, else a(n) = a(n-1) + p^((n-1)/2), where p=4. ; 1,4,8,20,36,84,148,340,596,1364,2388,5460,9556,21844,38228,87380,152916,349524,611668,1398100,2446676,5592404,9786708,22369620,39146836,89478484,156587348,357913940,626349396,1431655764,2505397588,5726623060,10021590356,22906492244,40086361428,91625968980,160345445716,366503875924,641381782868,1466015503700,2565527131476,5864062014804,10262108525908,23456248059220,41048434103636,93824992236884,164193736414548,375299968947540,656774945658196,1501199875790164,2627099782632788,6004799503160660 mov $1,1 mov $2,1 mov $3,1 lpb $0,1 sub $0,1 sub $1,$2 mul $3,2 mov $2,$3 add $2,$1 sub $3,1 mov $1,$3 add $3,1 add $1,$3 mul $1,2 sub $2,1 sub $1,$2 sub $1,1 add $2,1 lpe
; A063915: G.f.: (1 + Sum_{ i >= 0 } 2^i*x^(2^(i+1)-1)) / (1-x)^2. ; 1,3,5,9,13,17,21,29,37,45,53,61,69,77,85,101,117,133,149,165,181,197,213,229,245,261,277,293,309,325,341,373,405,437,469,501,533,565,597,629,661,693,725,757,789,821,853,885,917,949,981,1013,1045,1077,1109,1141,1173,1205,1237,1269,1301,1333,1365,1429,1493,1557,1621,1685,1749,1813,1877,1941,2005,2069,2133,2197,2261,2325,2389,2453,2517,2581,2645,2709,2773,2837,2901,2965,3029,3093,3157,3221,3285,3349,3413,3477,3541,3605,3669,3733 mov $2,$0 add $2,1 mov $4,$0 lpb $2 mov $0,$4 sub $2,1 sub $0,$2 mov $3,1 lpb $0 sub $0,$3 mul $3,2 lpe add $1,$3 lpe mov $0,$1
//================================================================================================= /*! // \file src/mathtest/smatdmatschur/LCaLDb.cpp // \brief Source file for the LCaLDb sparse matrix/dense matrix Schur product math test // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/LowerMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatdmatschur/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'LCaLDb'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions using LCa = blaze::LowerMatrix< blaze::CompressedMatrix<TypeA> >; using LDb = blaze::LowerMatrix< blaze::DynamicMatrix<TypeB> >; // Creator type definitions using CLCa = blazetest::Creator<LCa>; using CLDb = blazetest::Creator<LDb>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=LCa::maxNonZeros( i ); ++j ) { RUN_SMATDMATSCHUR_OPERATION_TEST( CLCa( i, j ), CLDb( i ) ); } } // Running tests with large matrices RUN_SMATDMATSCHUR_OPERATION_TEST( CLCa( 67UL, 7UL ), CLDb( 67UL ) ); RUN_SMATDMATSCHUR_OPERATION_TEST( CLCa( 128UL, 16UL ), CLDb( 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix Schur product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
;/* ; Copyright Oliver Kowalke 2009. ; Distributed under the Boost Software License, Version 1.0. ; (See accompanying file LICENSE_1_0.txt or copy at ; http://www.boost.org/LICENSE_1_0.txt) ;*/ ; ******************************************************* ; * * ; * ------------------------------------------------- * ; * | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | * ; * ------------------------------------------------- * ; * | 0x0 | 0x4 | 0x8 | 0xc | 0x10| 0x14| 0x18| 0x1c| * ; * ------------------------------------------------- * ; * |deall|limit| base|hiddn| v1 | v2 | v3 | v4 | * ; * ------------------------------------------------- * ; * ------------------------------------------------- * ; * | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | * ; * ------------------------------------------------- * ; * | 0x20| 0x24| 0x28| 0x2c| 0x30| 0x34| 0x38| 0x3c| * ; * ------------------------------------------------- * ; * | v5 | v6 | v7 | v8 | lr | pc | FCTX| DATA| * ; * ------------------------------------------------- * ; * * ; ******************************************************* AREA |.text|, CODE ALIGN 4 EXPORT ostd_ontop_fcontext ostd_ontop_fcontext PROC ; save LR as PC push {lr} ; save hidden,V1-V8,LR push {a1,v1-v8,lr} ; load TIB to save/restore thread size and limit. ; we do not need preserve CPU flag and can use it's arg register mrc p15, #0, v1, c13, c0, #2 ; save current stack base ldr a1, [v1, #0x04] push {a1} ; save current stack limit ldr a1, [v1, #0x08] push {a1} ; save current deallocation stack ldr a1, [v1, #0xe0c] push {a1} ; store RSP (pointing to context-data) in A1 mov a1, sp ; restore RSP (pointing to context-data) from A2 mov sp, a2 ; restore stack base pop {a1} str a1, [v1, #0x04] ; restore stack limit pop {a1} str a1, [v1, #0x08] ; restore deallocation stack pop {a1} str a1, [v1, #0xe0c] ; store parent context in A2 mov a2, a1 ; restore hidden,V1-V8,LR pop {a1,v1-v8,lr} ; return transfer_t from jump str a2, [a1, #0] str a3, [a1, #4] ; pass transfer_t as first arg in context function ; A1 == hidden, A2 == FCTX, A3 == DATA ; skip PC add sp, sp, #4 ; jump to ontop-function bx a4 ENDP END
/* * * Copyright (c) 2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // THIS FILE IS GENERATED BY ZAP #include <app-common/zap-generated/callback.h> #include <app-common/zap-generated/cluster-id.h> #include <lib/support/Span.h> #include <protocols/interaction_model/Constants.h> using namespace chip; // Cluster Init Functions void emberAfClusterInitCallback(EndpointId endpoint, ClusterId clusterId) { switch (clusterId) { case ZCL_ADMINISTRATOR_COMMISSIONING_CLUSTER_ID: emberAfAdministratorCommissioningClusterInitCallback(endpoint); break; case ZCL_BASIC_CLUSTER_ID: emberAfBasicClusterInitCallback(endpoint); break; case ZCL_DESCRIPTOR_CLUSTER_ID: emberAfDescriptorClusterInitCallback(endpoint); break; case ZCL_DIAGNOSTIC_LOGS_CLUSTER_ID: emberAfDiagnosticLogsClusterInitCallback(endpoint); break; case ZCL_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_ID: emberAfEthernetNetworkDiagnosticsClusterInitCallback(endpoint); break; case ZCL_FLOW_MEASUREMENT_CLUSTER_ID: emberAfFlowMeasurementClusterInitCallback(endpoint); break; case ZCL_GENERAL_COMMISSIONING_CLUSTER_ID: emberAfGeneralCommissioningClusterInitCallback(endpoint); break; case ZCL_GENERAL_DIAGNOSTICS_CLUSTER_ID: emberAfGeneralDiagnosticsClusterInitCallback(endpoint); break; case ZCL_LEVEL_CONTROL_CLUSTER_ID: emberAfLevelControlClusterInitCallback(endpoint); break; case ZCL_NETWORK_COMMISSIONING_CLUSTER_ID: emberAfNetworkCommissioningClusterInitCallback(endpoint); break; case ZCL_ON_OFF_CLUSTER_ID: emberAfOnOffClusterInitCallback(endpoint); break; case ZCL_OPERATIONAL_CREDENTIALS_CLUSTER_ID: emberAfOperationalCredentialsClusterInitCallback(endpoint); break; case ZCL_PRESSURE_MEASUREMENT_CLUSTER_ID: emberAfPressureMeasurementClusterInitCallback(endpoint); break; case ZCL_PUMP_CONFIG_CONTROL_CLUSTER_ID: emberAfPumpConfigurationAndControlClusterInitCallback(endpoint); break; case ZCL_SOFTWARE_DIAGNOSTICS_CLUSTER_ID: emberAfSoftwareDiagnosticsClusterInitCallback(endpoint); break; case ZCL_TEMP_MEASUREMENT_CLUSTER_ID: emberAfTemperatureMeasurementClusterInitCallback(endpoint); break; case ZCL_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_ID: emberAfThreadNetworkDiagnosticsClusterInitCallback(endpoint); break; case ZCL_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_ID: emberAfWiFiNetworkDiagnosticsClusterInitCallback(endpoint); break; default: // Unrecognized cluster ID break; } } void __attribute__((weak)) emberAfAdministratorCommissioningClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfBasicClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfDescriptorClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfDiagnosticLogsClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfEthernetNetworkDiagnosticsClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfFlowMeasurementClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfGeneralCommissioningClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfGeneralDiagnosticsClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfLevelControlClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfNetworkCommissioningClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfOnOffClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfOperationalCredentialsClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfPressureMeasurementClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfPumpConfigurationAndControlClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfSoftwareDiagnosticsClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfTemperatureMeasurementClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfThreadNetworkDiagnosticsClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(EndpointId endpoint) { // To prevent warning (void) endpoint; } // // Non-Cluster Related Callbacks // /** @brief Add To Current App Tasks * * This function is only useful to sleepy end devices. This function will note * the passed item as part of a set of tasks the application has outstanding * (e.g. message sent requiring APS acknwoledgement). This will affect how the * application behaves with regard to sleeping and polling. Until the * outstanding task is completed, the device may poll more frequently and sleep * less often. * * @param tasks Ver.: always */ void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} /** @brief Remove From Current App Tasks * * This function is only useful to sleepy end devices. This function will * remove the passed item from the set of tasks the application has outstanding * (e.g. message sent requiring APS acknwoledgement). This will affect how the * application behaves with regard to sleeping and polling. Removing the item * from the list of outstanding tasks may allow the device to sleep longer and * poll less frequently. If there are other outstanding tasks the system may * still have to stay away and poll more often. * * @param tasks Ver.: always */ void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {} /** @brief Allow Network Write Attribute * * This function is called by the application framework before it writes an * attribute in response to a write attribute request from an external device. * The value passed into this callback is the value to which the attribute is to * be set by the framework. Example: In mirroring simple metering data * on an Energy Services Interface (ESI) (formerly called Energy Service Portal * (ESP) in SE 1.0).), a mirrored simple meter needs to write read-only * attributes on its mirror. The-meter-mirror sample application, located in * app/framework/sample-apps, uses this callback to allow the mirrored device to * write simple metering attributes on the mirror regardless of the fact that * most simple metering attributes are defined as read-only by the ZigBee * specification. Note: The ZCL specification does not (as of this * writing) specify any permission-level security for writing writeable * attributes. As far as the ZCL specification is concerned, if an attribute is * writeable, any device that has a link key for the device should be able to * write that attribute. Furthermore if an attribute is read only, it should not * be written over the air. Thus, if you implement permissions for writing * attributes as a feature, you MAY be operating outside the specification. This * is unlikely to be a problem for writing read-only attributes, but it may be a * problem for attributes that are writeable according to the specification but * restricted by the application implementing this callback. * * @param endpoint Ver.: always * @param clusterId Ver.: always * @param attributeId Ver.: always * @param mask Ver.: always * @param manufacturerCode Ver.: always * @param value Ver.: always * @param type Ver.: always */ EmberAfAttributeWritePermission __attribute__((weak)) emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t mask, uint16_t manufacturerCode, uint8_t * value, uint8_t type) { return EMBER_ZCL_ATTRIBUTE_WRITE_PERMISSION_ALLOW_WRITE_NORMAL; // Default } /** @brief Attribute Read Access * * This function is called whenever the Application Framework needs to check * access permission for an attribute read. * * @param endpoint Ver.: always * @param clusterId Ver.: always * @param manufacturerCode Ver.: always * @param attributeId Ver.: always */ bool __attribute__((weak)) emberAfAttributeReadAccessCallback(EndpointId endpoint, ClusterId clusterId, uint16_t manufacturerCode, AttributeId attributeId) { return true; } /** @brief Attribute Write Access * * This function is called whenever the Application Framework needs to check * access permission for an attribute write. * * @param endpoint Ver.: always * @param clusterId Ver.: always * @param manufacturerCode Ver.: always * @param attributeId Ver.: always */ bool __attribute__((weak)) emberAfAttributeWriteAccessCallback(EndpointId endpoint, ClusterId clusterId, uint16_t manufacturerCode, AttributeId attributeId) { return true; } /** @brief Default Response * * This function is called by the application framework when a Default Response * command is received from an external device. The application should return * true if the message was processed or false if it was not. * * @param clusterId The cluster identifier of this response. Ver.: always * @param commandId The command identifier to which this is a response. Ver.: * always * @param status Specifies either SUCCESS or the nature of the error that was * detected in the received command. Ver.: always */ bool __attribute__((weak)) emberAfDefaultResponseCallback(ClusterId clusterId, CommandId commandId, EmberAfStatus status) { return false; } /** @brief Pre Message Send * * This function is called by the framework when it is about to pass a message * to the stack primitives for sending. This message may or may not be ZCL, * ZDO, or some other protocol. This is called prior to any ZigBee * fragmentation that may be done. If the function returns true it is assumed * the callback has consumed and processed the message. The callback must also * set the EmberStatus status code to be passed back to the caller. The * framework will do no further processing on the message. If the * function returns false then it is assumed that the callback has not processed * the mesasge and the framework will continue to process accordingly. * * @param messageStruct The structure containing the parameters of the APS * message to be sent. Ver.: always * @param status A pointer to the status code value that will be returned to the * caller. Ver.: always */ bool __attribute__((weak)) emberAfPreMessageSendCallback(EmberAfMessageStruct * messageStruct, EmberStatus * status) { return false; } /** @brief Message Sent * * This function is called by the application framework from the message sent * handler, when it is informed by the stack regarding the message sent status. * All of the values passed to the emberMessageSentHandler are passed on to this * callback. This provides an opportunity for the application to verify that its * message has been sent successfully and take the appropriate action. This * callback should return a bool value of true or false. A value of true * indicates that the message sent notification has been handled and should not * be handled by the application framework. * * @param type Ver.: always * @param destination Ver.: always * @param apsFrame Ver.: always * @param msgLen Ver.: always * @param message Ver.: always * @param status Ver.: always */ bool __attribute__((weak)) emberAfMessageSentCallback(const MessageSendDestination & destination, EmberApsFrame * apsFrame, uint16_t msgLen, uint8_t * message, EmberStatus status) { return false; } /** @brief External Attribute Read * * Like emberAfExternalAttributeWriteCallback above, this function is called * when the framework needs to read an attribute that is not stored within the * Application Framework's data structures. All of the important * information about the attribute itself is passed as a pointer to an * EmberAfAttributeMetadata struct, which is stored within the application and * used to manage the attribute. A complete description of the * EmberAfAttributeMetadata struct is provided in * app/framework/include/af-types.h This function assumes that the * application is able to read the attribute, write it into the passed buffer, * and return immediately. Any attributes that require a state machine for * reading and writing are not really candidates for externalization at the * present time. The Application Framework does not currently include a state * machine for reading or writing attributes that must take place across a * series of application ticks. Attributes that cannot be read in a timely * manner should be stored within the Application Framework and updated * occasionally by the application code from within the * emberAfMainTickCallback. If the application was successfully able to * read the attribute and write it into the passed buffer, it should return a * value of EMBER_ZCL_STATUS_SUCCESS. Ensure that the size of the externally * managed attribute value is smaller than what the buffer can hold. In the case * of a buffer overflow throw an appropriate error such as * EMBER_ZCL_STATUS_INSUFFICIENT_SPACE. Any other return value indicates the * application was not able to read the attribute. * * @param endpoint Ver.: always * @param clusterId Ver.: always * @param attributeMetadata Ver.: always * @param manufacturerCode Ver.: always * @param buffer Ver.: always * @param maxReadLength Ver.: always * @param index Ver.: always */ EmberAfStatus __attribute__((weak)) emberAfExternalAttributeReadCallback(EndpointId endpoint, ClusterId clusterId, EmberAfAttributeMetadata * attributeMetadata, uint16_t manufacturerCode, uint8_t * buffer, uint16_t maxReadLength, int32_t index) { return EMBER_ZCL_STATUS_FAILURE; } /** @brief External Attribute Write * * This function is called whenever the Application Framework needs to write an * attribute which is not stored within the data structures of the Application * Framework itself. One of the new features in Version 2 is the ability to * store attributes outside the Framework. This is particularly useful for * attributes that do not need to be stored because they can be read off the * hardware when they are needed, or are stored in some central location used by * many modules within the system. In this case, you can indicate that the * attribute is stored externally. When the framework needs to write an external * attribute, it makes a call to this callback. This callback is very * useful for host micros which need to store attributes in persistent memory. * Because each host micro (used with an Ember NCP) has its own type of * persistent memory storage, the Application Framework does not include the * ability to mark attributes as stored in flash the way that it does for Ember * SoCs like the EM35x. On a host micro, any attributes that need to be stored * in persistent memory should be marked as external and accessed through the * external read and write callbacks. Any host code associated with the * persistent storage should be implemented within this callback. All of * the important information about the attribute itself is passed as a pointer * to an EmberAfAttributeMetadata struct, which is stored within the application * and used to manage the attribute. A complete description of the * EmberAfAttributeMetadata struct is provided in * app/framework/include/af-types.h. This function assumes that the * application is able to write the attribute and return immediately. Any * attributes that require a state machine for reading and writing are not * candidates for externalization at the present time. The Application Framework * does not currently include a state machine for reading or writing attributes * that must take place across a series of application ticks. Attributes that * cannot be written immediately should be stored within the Application * Framework and updated occasionally by the application code from within the * emberAfMainTickCallback. If the application was successfully able to * write the attribute, it returns a value of EMBER_ZCL_STATUS_SUCCESS. Any * other return value indicates the application was not able to write the * attribute. * * @param endpoint Ver.: always * @param clusterId Ver.: always * @param attributeMetadata Ver.: always * @param manufacturerCode Ver.: always * @param buffer Ver.: always * @param index Ver.: always */ EmberAfStatus __attribute__((weak)) emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, EmberAfAttributeMetadata * attributeMetadata, uint16_t manufacturerCode, uint8_t * buffer, int32_t index) { return EMBER_ZCL_STATUS_FAILURE; } /** @brief Get Current Time * * This callback is called when device attempts to get current time from the * hardware. If this device has means to retrieve exact time, then this method * should implement it. If the callback can't provide the exact time it should * return 0 to indicate failure. Default action is to return 0, which indicates * that device does not have access to real time. * */ uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback() { return 0; } /** @brief Get Endpoint Info * * This function is a callback to an application implemented endpoint that * operates outside the normal application framework. When the framework wishes * to perform operations with that endpoint it uses this callback to retrieve * the endpoint's information. If the endpoint exists and the application can * provide data then true shall be returned. Otherwise the callback must return * false. * * @param endpoint The endpoint to retrieve data for. Ver.: always * @param returnNetworkIndex The index corresponding to the ZigBee network the * endpoint belongs to. If not using a multi-network device, 0 must be * returned. Otherwise on a multi-network device the stack will switch to this * network before sending the message. Ver.: always * @param returnEndpointInfo A pointer to a data struct that will be written * with information about the endpoint. Ver.: always */ bool __attribute__((weak)) emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo) { return false; } /** @brief Registration Abort * * This callback is called when the device should abort the registration * process. * */ void __attribute__((weak)) emberAfRegistrationAbortCallback() {} /** @brief Interpan Send Message * * This function will send a raw MAC message with interpan frame format using * the passed parameters. * * @param header Interpan header info Ver.: always * @param messageLength The length of the message received or to send Ver.: * always * @param message The message data received or to send. Ver.: always */ EmberStatus __attribute__((weak)) emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message) { return EMBER_LIBRARY_NOT_PRESENT; } /** @brief Start Move * * This function is called to initiate the process for a device to move (rejoin) * to a new parent. * */ bool __attribute__((weak)) emberAfStartMoveCallback() { return false; } /** @brief Pre Attribute Change * * This function is called by the application framework before it changes an * attribute value. The value passed into this callback is the value to which * the attribute is to be set by the framework. The application should return * chip::Protocols::InteractionModel::Status::Success to permit the change or * any other code to reject it. * * @param attributePath * @param mask * @param type * @param size * @param value */ chip::Protocols::InteractionModel::Status __attribute__((weak)) MatterPreAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t mask, uint8_t type, uint16_t size, uint8_t * value) { return chip::Protocols::InteractionModel::Status::Success; } /** @brief Post Attribute Change * * This function is called by the application framework after it changes an * attribute value. The value passed into this callback is the value to which * the attribute was set by the framework. * * @param attributePath * @param mask * @param type * @param size * @param value */ void __attribute__((weak)) MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t mask, uint8_t type, uint16_t size, uint8_t * value) {}
; A337484: Number of ordered triples of positive integers summing to n that are neither strictly increasing nor strictly decreasing. ; 0,0,0,1,3,6,8,13,17,22,28,35,41,50,58,67,77,88,98,111,123,136,150,165,179,196,212,229,247,266,284,305,325,346,368,391,413,438,462,487,513,540,566,595,623,652,682,713,743,776,808,841,875,910,944,981,1017 mov $1,5 mov $3,$0 div $0,2 mov $2,4 pow $3,2 sub $3,1 div $3,3 sub $3,$0 add $2,$3 add $1,$2 sub $1,9
; A287272: a(n) is the number of zeros of the Laguerre L(n, x) polynomial in the open interval (-1, +1). ; 0,0,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 lpb $0 add $1,5 trn $0,$1 sub $0,1 lpe div $1,5
; A000127: Maximal number of regions obtained by joining n points around a circle by straight lines. Also number of regions in 4-space formed by n-1 hyperplanes. ; 1,2,4,8,16,31,57,99,163,256,386,562,794,1093,1471,1941,2517,3214,4048,5036,6196,7547,9109,10903,12951,15276,17902,20854,24158,27841,31931,36457,41449,46938,52956,59536,66712,74519,82993,92171,102091,112792,124314,136698,149986,164221,179447,195709,213053,231526,251176,272052,294204,317683,342541,368831,396607,425924,456838,489406,523686,559737,597619,637393,679121,722866,768692,816664,866848,919311,974121,1031347,1091059,1153328,1218226,1285826,1356202,1429429,1505583,1584741,1666981,1752382 mov $1,$0 bin $0,3 add $1,1 mul $1,2 mov $2,2 sub $2,$1 sub $0,$2 mul $0,$1 div $0,8 add $0,1
/* * Copyright 2011-2019 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include "bgfx_p.h" #if (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL) # include "renderer_gl.h" # include <bx/timer.h> # include <bx/uint32_t.h> namespace bgfx { namespace gl { static char s_viewName[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME]; inline void setViewType(ViewId _view, const bx::StringView _str) { if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION || BGFX_CONFIG_PROFILER) ) { bx::memCopy(&s_viewName[_view][3], _str.getPtr(), _str.getLength() ); } } struct PrimInfo { GLenum m_type; uint32_t m_min; uint32_t m_div; uint32_t m_sub; }; static const PrimInfo s_primInfo[] = { { GL_TRIANGLES, 3, 3, 0 }, { GL_TRIANGLE_STRIP, 3, 1, 2 }, { GL_LINES, 2, 2, 0 }, { GL_LINE_STRIP, 2, 1, 1 }, { GL_POINTS, 1, 1, 0 }, { GL_ZERO, 0, 0, 0 }, }; BX_STATIC_ASSERT(Topology::Count == BX_COUNTOF(s_primInfo)-1); static const char* s_attribName[] = { "a_position", "a_normal", "a_tangent", "a_bitangent", "a_color0", "a_color1", "a_color2", "a_color3", "a_indices", "a_weight", "a_texcoord0", "a_texcoord1", "a_texcoord2", "a_texcoord3", "a_texcoord4", "a_texcoord5", "a_texcoord6", "a_texcoord7", }; BX_STATIC_ASSERT(Attrib::Count == BX_COUNTOF(s_attribName) ); static const char* s_instanceDataName[] = { "i_data0", "i_data1", "i_data2", "i_data3", "i_data4", }; BX_STATIC_ASSERT(BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT == BX_COUNTOF(s_instanceDataName) ); static const GLenum s_access[] = { GL_READ_ONLY, GL_WRITE_ONLY, GL_READ_WRITE, }; BX_STATIC_ASSERT(Access::Count == BX_COUNTOF(s_access) ); static const GLenum s_attribType[] = { GL_UNSIGNED_BYTE, // Uint8 GL_UNSIGNED_INT_10_10_10_2, // Uint10 GL_SHORT, // Int16 GL_HALF_FLOAT, // Half GL_FLOAT, // Float }; BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) ); struct Blend { GLenum m_src; GLenum m_dst; bool m_factor; }; static const Blend s_blendFactor[] = { { 0, 0, false }, // ignored { GL_ZERO, GL_ZERO, false }, // ZERO { GL_ONE, GL_ONE, false }, // ONE { GL_SRC_COLOR, GL_SRC_COLOR, false }, // SRC_COLOR { GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, false }, // INV_SRC_COLOR { GL_SRC_ALPHA, GL_SRC_ALPHA, false }, // SRC_ALPHA { GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, false }, // INV_SRC_ALPHA { GL_DST_ALPHA, GL_DST_ALPHA, false }, // DST_ALPHA { GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, false }, // INV_DST_ALPHA { GL_DST_COLOR, GL_DST_COLOR, false }, // DST_COLOR { GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR, false }, // INV_DST_COLOR { GL_SRC_ALPHA_SATURATE, GL_ONE, false }, // SRC_ALPHA_SAT { GL_CONSTANT_COLOR, GL_CONSTANT_COLOR, true }, // FACTOR { GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, true }, // INV_FACTOR }; static const GLenum s_blendEquation[] = { GL_FUNC_ADD, GL_FUNC_SUBTRACT, GL_FUNC_REVERSE_SUBTRACT, GL_MIN, GL_MAX, }; static const GLenum s_cmpFunc[] = { 0, // ignored GL_LESS, GL_LEQUAL, GL_EQUAL, GL_GEQUAL, GL_GREATER, GL_NOTEQUAL, GL_NEVER, GL_ALWAYS, }; static const GLenum s_stencilOp[] = { GL_ZERO, GL_KEEP, GL_REPLACE, GL_INCR_WRAP, GL_INCR, GL_DECR_WRAP, GL_DECR, GL_INVERT, }; static const GLenum s_stencilFace[] = { GL_FRONT_AND_BACK, GL_FRONT, GL_BACK, }; static GLenum s_textureAddress[] = { GL_REPEAT, GL_MIRRORED_REPEAT, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, }; static const GLenum s_textureFilterMag[] = { GL_LINEAR, GL_NEAREST, GL_LINEAR, }; static const GLenum s_textureFilterMin[][3] = { { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_NEAREST }, { GL_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_NEAREST }, { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_NEAREST }, }; struct TextureFormatInfo { GLenum m_internalFmt; GLenum m_internalFmtSrgb; GLenum m_fmt; GLenum m_type; bool m_supported; }; static TextureFormatInfo s_textureFormat[] = { { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_ZERO, false }, // BC1 { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_ZERO, false }, // BC2 { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_ZERO, false }, // BC3 { GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, false }, // BC4 { GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, false }, // BC5 { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, false }, // BC6H { GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, false }, // BC7 { GL_ETC1_RGB8_OES, GL_ZERO, GL_ETC1_RGB8_OES, GL_ZERO, false }, // ETC1 { GL_COMPRESSED_RGB8_ETC2, GL_ZERO, GL_COMPRESSED_RGB8_ETC2, GL_ZERO, false }, // ETC2 { GL_COMPRESSED_RGBA8_ETC2_EAC, GL_COMPRESSED_SRGB8_ETC2, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_ZERO, false }, // ETC2A { GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_ZERO, false }, // ETC2A1 { GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12 { GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14 { GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12A { GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14A { GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, false }, // PTC22 { GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, false }, // PTC24 { GL_ATC_RGB_AMD, GL_ZERO, GL_ATC_RGB_AMD, GL_ZERO, false }, // ATC { GL_ATC_RGBA_EXPLICIT_ALPHA_AMD, GL_ZERO, GL_ATC_RGBA_EXPLICIT_ALPHA_AMD, GL_ZERO, false }, // ATCE { GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD, GL_ZERO, GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD, GL_ZERO, false }, // ATCI { GL_COMPRESSED_RGBA_ASTC_4x4_KHR, GL_COMPRESSED_SRGB8_ASTC_4x4_KHR, GL_COMPRESSED_RGBA_ASTC_4x4_KHR, GL_ZERO, false }, // ASTC4x4 { GL_COMPRESSED_RGBA_ASTC_5x5_KHR, GL_COMPRESSED_SRGB8_ASTC_5x5_KHR, GL_COMPRESSED_RGBA_ASTC_5x5_KHR, GL_ZERO, false }, // ASTC5x5 { GL_COMPRESSED_RGBA_ASTC_6x6_KHR, GL_COMPRESSED_SRGB8_ASTC_6x6_KHR, GL_COMPRESSED_RGBA_ASTC_6x6_KHR, GL_ZERO, false }, // ASTC6x6 { GL_COMPRESSED_RGBA_ASTC_8x5_KHR, GL_COMPRESSED_SRGB8_ASTC_8x5_KHR, GL_COMPRESSED_RGBA_ASTC_8x5_KHR, GL_ZERO, false }, // ASTC8x5 { GL_COMPRESSED_RGBA_ASTC_8x6_KHR, GL_COMPRESSED_SRGB8_ASTC_8x6_KHR, GL_COMPRESSED_RGBA_ASTC_8x6_KHR, GL_ZERO, false }, // ASTC8x6 { GL_COMPRESSED_RGBA_ASTC_10x5_KHR, GL_COMPRESSED_SRGB8_ASTC_10x5_KHR, GL_COMPRESSED_RGBA_ASTC_10x5_KHR, GL_ZERO, false }, // ASTC10x5 { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // Unknown { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // R1 { GL_ALPHA, GL_ZERO, GL_ALPHA, GL_UNSIGNED_BYTE, false }, // A8 { GL_R8, GL_ZERO, GL_RED, GL_UNSIGNED_BYTE, false }, // R8 { GL_R8I, GL_ZERO, GL_RED, GL_BYTE, false }, // R8I { GL_R8UI, GL_ZERO, GL_RED, GL_UNSIGNED_BYTE, false }, // R8U { GL_R8_SNORM, GL_ZERO, GL_RED, GL_BYTE, false }, // R8S { GL_R16, GL_ZERO, GL_RED, GL_UNSIGNED_SHORT, false }, // R16 { GL_R16I, GL_ZERO, GL_RED, GL_SHORT, false }, // R16I { GL_R16UI, GL_ZERO, GL_RED, GL_UNSIGNED_SHORT, false }, // R16U { GL_R16F, GL_ZERO, GL_RED, GL_HALF_FLOAT, false }, // R16F { GL_R16_SNORM, GL_ZERO, GL_RED, GL_SHORT, false }, // R16S { GL_R32I, GL_ZERO, GL_RED, GL_INT, false }, // R32I { GL_R32UI, GL_ZERO, GL_RED, GL_UNSIGNED_INT, false }, // R32U { GL_R32F, GL_ZERO, GL_RED, GL_FLOAT, false }, // R32F { GL_RG8, GL_ZERO, GL_RG, GL_UNSIGNED_BYTE, false }, // RG8 { GL_RG8I, GL_ZERO, GL_RG, GL_BYTE, false }, // RG8I { GL_RG8UI, GL_ZERO, GL_RG, GL_UNSIGNED_BYTE, false }, // RG8U { GL_RG8_SNORM, GL_ZERO, GL_RG, GL_BYTE, false }, // RG8S { GL_RG16, GL_ZERO, GL_RG, GL_UNSIGNED_SHORT, false }, // RG16 { GL_RG16I, GL_ZERO, GL_RG, GL_SHORT, false }, // RG16I { GL_RG16UI, GL_ZERO, GL_RG, GL_UNSIGNED_SHORT, false }, // RG16U { GL_RG16F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG16F { GL_RG16_SNORM, GL_ZERO, GL_RG, GL_SHORT, false }, // RG16S { GL_RG32I, GL_ZERO, GL_RG, GL_INT, false }, // RG32I { GL_RG32UI, GL_ZERO, GL_RG, GL_UNSIGNED_INT, false }, // RG32U { GL_RG32F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG32F { GL_RGB8, GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE, false }, // RGB8 { GL_RGB8I, GL_ZERO, GL_RGB, GL_BYTE, false }, // RGB8I { GL_RGB8UI, GL_ZERO, GL_RGB, GL_UNSIGNED_BYTE, false }, // RGB8U { GL_RGB8_SNORM, GL_ZERO, GL_RGB, GL_BYTE, false }, // RGB8S { GL_RGB9_E5, GL_ZERO, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, false }, // RGB9E5F { GL_RGBA8, GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE, false }, // BGRA8 { GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA8 { GL_RGBA8I, GL_ZERO, GL_RGBA, GL_BYTE, false }, // RGBA8I { GL_RGBA8UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA8U { GL_RGBA8_SNORM, GL_ZERO, GL_RGBA, GL_BYTE, false }, // RGBA8S { GL_RGBA16, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT, false }, // RGBA16 { GL_RGBA16I, GL_ZERO, GL_RGBA, GL_SHORT, false }, // RGBA16I { GL_RGBA16UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT, false }, // RGBA16U { GL_RGBA16F, GL_ZERO, GL_RGBA, GL_HALF_FLOAT, false }, // RGBA16F { GL_RGBA16_SNORM, GL_ZERO, GL_RGBA, GL_SHORT, false }, // RGBA16S { GL_RGBA32I, GL_ZERO, GL_RGBA, GL_INT, false }, // RGBA32I { GL_RGBA32UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT, false }, // RGBA32U { GL_RGBA32F, GL_ZERO, GL_RGBA, GL_FLOAT, false }, // RGBA32F { GL_RGB565, GL_ZERO, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, false }, // R5G6B5 { GL_RGBA4, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV, false }, // RGBA4 { GL_RGB5_A1, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV, false }, // RGB5A1 { GL_RGB10_A2, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false }, // RGB10A2 { GL_R11F_G11F_B10F, GL_ZERO, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false }, // RG11B10F { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // UnknownDepth { GL_DEPTH_COMPONENT16, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false }, // D16 { GL_DEPTH_COMPONENT24, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D24 { GL_DEPTH24_STENCIL8, GL_ZERO, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false }, // D24S8 { GL_DEPTH_COMPONENT32, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D32 { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D16F { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D24F { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D32F { GL_STENCIL_INDEX8, GL_ZERO, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, false }, // D0S8 }; BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) ); static bool s_textureFilter[TextureFormat::Count+1]; static GLenum s_rboFormat[] = { GL_ZERO, // BC1 GL_ZERO, // BC2 GL_ZERO, // BC3 GL_ZERO, // BC4 GL_ZERO, // BC5 GL_ZERO, // BC6H GL_ZERO, // BC7 GL_ZERO, // ETC1 GL_ZERO, // ETC2 GL_ZERO, // ETC2A GL_ZERO, // ETC2A1 GL_ZERO, // PTC12 GL_ZERO, // PTC14 GL_ZERO, // PTC12A GL_ZERO, // PTC14A GL_ZERO, // PTC22 GL_ZERO, // PTC24 GL_ZERO, // ATC GL_ZERO, // ATCE GL_ZERO, // ATCI GL_ZERO, // ASTC4x4 GL_ZERO, // ASTC5x5 GL_ZERO, // ASTC6x6 GL_ZERO, // ASTC8x5 GL_ZERO, // ASTC8x6 GL_ZERO, // ASTC10x5 GL_ZERO, // Unknown GL_ZERO, // R1 GL_ALPHA, // A8 GL_R8, // R8 GL_R8I, // R8I GL_R8UI, // R8U GL_R8_SNORM, // R8S GL_R16, // R16 GL_R16I, // R16I GL_R16UI, // R16U GL_R16F, // R16F GL_R16_SNORM, // R16S GL_R32I, // R32I GL_R32UI, // R32U GL_R32F, // R32F GL_RG8, // RG8 GL_RG8I, // RG8I GL_RG8UI, // RG8U GL_RG8_SNORM, // RG8S GL_RG16, // RG16 GL_RG16I, // RG16I GL_RG16UI, // RG16U GL_RG16F, // RG16F GL_RG16_SNORM, // RG16S GL_RG32I, // RG32I GL_RG32UI, // RG32U GL_RG32F, // RG32F GL_RGB8, // RGB8 GL_RGB8I, // RGB8I GL_RGB8UI, // RGB8UI GL_RGB8_SNORM, // RGB8S GL_RGB9_E5, // RGB9E5F GL_RGBA8, // BGRA8 GL_RGBA8, // RGBA8 GL_RGBA8I, // RGBA8I GL_RGBA8UI, // RGBA8UI GL_RGBA8_SNORM, // RGBA8S GL_RGBA16, // RGBA16 GL_RGBA16I, // RGBA16I GL_RGBA16UI, // RGBA16U GL_RGBA16F, // RGBA16F GL_RGBA16_SNORM, // RGBA16S GL_RGBA32I, // RGBA32I GL_RGBA32UI, // RGBA32U GL_RGBA32F, // RGBA32F GL_RGB565, // R5G6B5 GL_RGBA4, // RGBA4 GL_RGB5_A1, // RGB5A1 GL_RGB10_A2, // RGB10A2 GL_R11F_G11F_B10F, // RG11B10F GL_ZERO, // UnknownDepth GL_DEPTH_COMPONENT16, // D16 GL_DEPTH_COMPONENT24, // D24 GL_DEPTH24_STENCIL8, // D24S8 GL_DEPTH_COMPONENT32, // D32 GL_DEPTH_COMPONENT32F, // D16F GL_DEPTH_COMPONENT32F, // D24F GL_DEPTH_COMPONENT32F, // D32F GL_STENCIL_INDEX8, // D0S8 }; BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_rboFormat) ); static GLenum s_imageFormat[] = { GL_ZERO, // BC1 GL_ZERO, // BC2 GL_ZERO, // BC3 GL_ZERO, // BC4 GL_ZERO, // BC5 GL_ZERO, // BC6H GL_ZERO, // BC7 GL_ZERO, // ETC1 GL_ZERO, // ETC2 GL_ZERO, // ETC2A GL_ZERO, // ETC2A1 GL_ZERO, // PTC12 GL_ZERO, // PTC14 GL_ZERO, // PTC12A GL_ZERO, // PTC14A GL_ZERO, // PTC22 GL_ZERO, // PTC24 GL_ZERO, // ATC GL_ZERO, // ATCE GL_ZERO, // ATCI GL_ZERO, // ASTC4x4 GL_ZERO, // ASTC5x5 GL_ZERO, // ASTC6x6 GL_ZERO, // ASTC8x5 GL_ZERO, // ASTC8x6 GL_ZERO, // ASTC10x5 GL_ZERO, // Unknown GL_ZERO, // R1 GL_ALPHA, // A8 GL_R8, // R8 GL_R8I, // R8I GL_R8UI, // R8UI GL_R8_SNORM, // R8S GL_R16, // R16 GL_R16I, // R16I GL_R16UI, // R16U GL_R16F, // R16F GL_R16_SNORM, // R16S GL_R32I, // R32I GL_R32UI, // R32U GL_R32F, // R32F GL_RG8, // RG8 GL_RG8I, // RG8I GL_RG8UI, // RG8U GL_RG8_SNORM, // RG8S GL_RG16, // RG16 GL_RG16I, // RG16I GL_RG16UI, // RG16U GL_RG16F, // RG16F GL_RG16_SNORM, // RG16S GL_RG32I, // RG32I GL_RG32UI, // RG32U GL_RG32F, // RG32F GL_RGB8, // RGB8 GL_RGB8I, // RGB8I GL_RGB8UI, // RGB8UI GL_RGB8_SNORM, // RGB8S GL_RGB9_E5, // RGB9E5F GL_RGBA8, // BGRA8 GL_RGBA8, // RGBA8 GL_RGBA8I, // RGBA8I GL_RGBA8UI, // RGBA8UI GL_RGBA8_SNORM, // RGBA8S GL_RGBA16, // RGBA16 GL_RGBA16I, // RGBA16I GL_RGBA16UI, // RGBA16U GL_RGBA16F, // RGBA16F GL_RGBA16_SNORM, // RGBA16S GL_RGBA32I, // RGBA32I GL_RGBA32UI, // RGBA32U GL_RGBA32F, // RGBA32F GL_RGB565, // R5G6B5 GL_RGBA4, // RGBA4 GL_RGB5_A1, // RGB5A1 GL_RGB10_A2, // RGB10A2 GL_R11F_G11F_B10F, // RG11B10F GL_ZERO, // UnknownDepth GL_ZERO, // D16 GL_ZERO, // D24 GL_ZERO, // D24S8 GL_ZERO, // D32 GL_ZERO, // D16F GL_ZERO, // D24F GL_ZERO, // D32F GL_ZERO, // D0S8 }; BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_imageFormat) ); struct Extension { enum Enum { AMD_conservative_depth, AMD_multi_draw_indirect, ANGLE_depth_texture, ANGLE_framebuffer_blit, ANGLE_framebuffer_multisample, ANGLE_instanced_arrays, ANGLE_texture_compression_dxt1, ANGLE_texture_compression_dxt3, ANGLE_texture_compression_dxt5, ANGLE_timer_query, ANGLE_translated_shader_source, APPLE_texture_format_BGRA8888, APPLE_texture_max_level, ARB_clip_control, ARB_compute_shader, ARB_conservative_depth, ARB_copy_image, ARB_debug_label, ARB_debug_output, ARB_depth_buffer_float, ARB_depth_clamp, ARB_draw_buffers_blend, ARB_draw_indirect, ARB_draw_instanced, ARB_ES3_compatibility, ARB_framebuffer_object, ARB_framebuffer_sRGB, ARB_get_program_binary, ARB_half_float_pixel, ARB_half_float_vertex, ARB_instanced_arrays, ARB_internalformat_query, ARB_internalformat_query2, ARB_invalidate_subdata, ARB_map_buffer_range, ARB_multi_draw_indirect, ARB_multisample, ARB_occlusion_query, ARB_occlusion_query2, ARB_program_interface_query, ARB_sampler_objects, ARB_seamless_cube_map, ARB_shader_bit_encoding, ARB_shader_image_load_store, ARB_shader_storage_buffer_object, ARB_shader_texture_lod, ARB_texture_compression_bptc, ARB_texture_compression_rgtc, ARB_texture_cube_map_array, ARB_texture_float, ARB_texture_multisample, ARB_texture_rg, ARB_texture_rgb10_a2ui, ARB_texture_stencil8, ARB_texture_storage, ARB_texture_swizzle, ARB_timer_query, ARB_uniform_buffer_object, ARB_vertex_array_object, ARB_vertex_type_2_10_10_10_rev, ATI_meminfo, CHROMIUM_color_buffer_float_rgb, CHROMIUM_color_buffer_float_rgba, CHROMIUM_depth_texture, CHROMIUM_framebuffer_multisample, CHROMIUM_texture_compression_dxt3, CHROMIUM_texture_compression_dxt5, EXT_bgra, EXT_blend_color, EXT_blend_minmax, EXT_blend_subtract, EXT_color_buffer_half_float, EXT_color_buffer_float, EXT_copy_image, EXT_compressed_ETC1_RGB8_sub_texture, EXT_debug_label, EXT_debug_marker, EXT_debug_tool, EXT_discard_framebuffer, EXT_disjoint_timer_query, EXT_draw_buffers, EXT_draw_instanced, EXT_instanced_arrays, EXT_frag_depth, EXT_framebuffer_blit, EXT_framebuffer_object, EXT_framebuffer_sRGB, EXT_gpu_shader4, EXT_multi_draw_indirect, EXT_occlusion_query_boolean, EXT_packed_float, EXT_read_format_bgra, EXT_shader_image_load_store, EXT_shader_texture_lod, EXT_shadow_samplers, EXT_sRGB_write_control, EXT_texture_array, EXT_texture_compression_dxt1, EXT_texture_compression_latc, EXT_texture_compression_rgtc, EXT_texture_compression_s3tc, EXT_texture_cube_map_array, EXT_texture_filter_anisotropic, EXT_texture_format_BGRA8888, EXT_texture_rg, EXT_texture_shared_exponent, EXT_texture_snorm, EXT_texture_sRGB, EXT_texture_storage, EXT_texture_swizzle, EXT_texture_type_2_10_10_10_REV, EXT_timer_query, EXT_unpack_subimage, GOOGLE_depth_texture, IMG_multisampled_render_to_texture, IMG_read_format, IMG_shader_binary, IMG_texture_compression_pvrtc, IMG_texture_compression_pvrtc2, IMG_texture_format_BGRA8888, INTEL_fragment_shader_ordering, KHR_debug, KHR_no_error, MOZ_WEBGL_compressed_texture_s3tc, MOZ_WEBGL_depth_texture, NV_conservative_raster, NV_copy_image, NV_draw_buffers, NV_occlusion_query, NV_texture_border_clamp, NVX_gpu_memory_info, OES_copy_image, OES_compressed_ETC1_RGB8_texture, OES_depth24, OES_depth32, OES_depth_texture, OES_element_index_uint, OES_fragment_precision_high, OES_get_program_binary, OES_required_internalformat, OES_packed_depth_stencil, OES_read_format, OES_rgb8_rgba8, OES_standard_derivatives, OES_texture_3D, OES_texture_float, OES_texture_float_linear, OES_texture_npot, OES_texture_half_float, OES_texture_half_float_linear, OES_texture_stencil8, OES_texture_storage_multisample_2d_array, OES_vertex_array_object, OES_vertex_half_float, OES_vertex_type_10_10_10_2, WEBGL_color_buffer_float, WEBGL_compressed_texture_etc1, WEBGL_compressed_texture_s3tc, WEBGL_compressed_texture_pvrtc, WEBGL_depth_texture, WEBGL_draw_buffers, WEBKIT_EXT_texture_filter_anisotropic, WEBKIT_WEBGL_compressed_texture_s3tc, WEBKIT_WEBGL_depth_texture, Count }; const char* m_name; bool m_supported; bool m_initialize; }; // Extension registry // // ANGLE: // https://github.com/google/angle/tree/master/extensions // // CHROMIUM: // https://chromium.googlesource.com/chromium/src.git/+/refs/heads/git-svn/gpu/GLES2/extensions/CHROMIUM // // EGL: // https://www.khronos.org/registry/egl/extensions/ // // GL: // https://www.opengl.org/registry/ // // GLES: // https://www.khronos.org/registry/gles/extensions/ // // WEBGL: // https://www.khronos.org/registry/webgl/extensions/ // static Extension s_extension[] = { { "AMD_conservative_depth", false, true }, { "AMD_multi_draw_indirect", false, true }, { "ANGLE_depth_texture", false, true }, { "ANGLE_framebuffer_blit", false, true }, { "ANGLE_framebuffer_multisample", false, false }, { "ANGLE_instanced_arrays", false, true }, { "ANGLE_texture_compression_dxt1", false, true }, { "ANGLE_texture_compression_dxt3", false, true }, { "ANGLE_texture_compression_dxt5", false, true }, { "ANGLE_timer_query", false, true }, { "ANGLE_translated_shader_source", false, true }, { "APPLE_texture_format_BGRA8888", false, true }, { "APPLE_texture_max_level", false, true }, { "ARB_clip_control", BGFX_CONFIG_RENDERER_OPENGL >= 43, true }, { "ARB_compute_shader", BGFX_CONFIG_RENDERER_OPENGL >= 43, true }, { "ARB_conservative_depth", BGFX_CONFIG_RENDERER_OPENGL >= 42, true }, { "ARB_copy_image", BGFX_CONFIG_RENDERER_OPENGL >= 42, true }, { "ARB_debug_label", false, true }, { "ARB_debug_output", BGFX_CONFIG_RENDERER_OPENGL >= 43, true }, { "ARB_depth_buffer_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "ARB_depth_clamp", BGFX_CONFIG_RENDERER_OPENGL >= 32, true }, { "ARB_draw_buffers_blend", BGFX_CONFIG_RENDERER_OPENGL >= 40, true }, { "ARB_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 40, true }, { "ARB_draw_instanced", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "ARB_ES3_compatibility", BGFX_CONFIG_RENDERER_OPENGL >= 43, true }, { "ARB_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "ARB_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "ARB_get_program_binary", BGFX_CONFIG_RENDERER_OPENGL >= 41, true }, { "ARB_half_float_pixel", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "ARB_half_float_vertex", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "ARB_instanced_arrays", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "ARB_internalformat_query", BGFX_CONFIG_RENDERER_OPENGL >= 42, true }, { "ARB_internalformat_query2", BGFX_CONFIG_RENDERER_OPENGL >= 43, true }, { "ARB_invalidate_subdata", BGFX_CONFIG_RENDERER_OPENGL >= 43, true }, { "ARB_map_buffer_range", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "ARB_multi_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 43, true }, { "ARB_multisample", false, true }, { "ARB_occlusion_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "ARB_occlusion_query2", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "ARB_program_interface_query", BGFX_CONFIG_RENDERER_OPENGL >= 43, true }, { "ARB_sampler_objects", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "ARB_seamless_cube_map", BGFX_CONFIG_RENDERER_OPENGL >= 32, true }, { "ARB_shader_bit_encoding", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "ARB_shader_image_load_store", BGFX_CONFIG_RENDERER_OPENGL >= 42, true }, { "ARB_shader_storage_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 43, true }, { "ARB_shader_texture_lod", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "ARB_texture_compression_bptc", BGFX_CONFIG_RENDERER_OPENGL >= 44, true }, { "ARB_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "ARB_texture_cube_map_array", BGFX_CONFIG_RENDERER_OPENGL >= 40, true }, { "ARB_texture_float", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "ARB_texture_multisample", BGFX_CONFIG_RENDERER_OPENGL >= 32, true }, { "ARB_texture_rg", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "ARB_texture_rgb10_a2ui", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "ARB_texture_stencil8", false, true }, { "ARB_texture_storage", BGFX_CONFIG_RENDERER_OPENGL >= 42, true }, { "ARB_texture_swizzle", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "ARB_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "ARB_uniform_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 31, true }, { "ARB_vertex_array_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "ARB_vertex_type_2_10_10_10_rev", false, true }, { "ATI_meminfo", false, true }, { "CHROMIUM_color_buffer_float_rgb", false, true }, { "CHROMIUM_color_buffer_float_rgba", false, true }, { "CHROMIUM_depth_texture", false, true }, { "CHROMIUM_framebuffer_multisample", false, true }, { "CHROMIUM_texture_compression_dxt3", false, true }, { "CHROMIUM_texture_compression_dxt5", false, true }, { "EXT_bgra", false, true }, { "EXT_blend_color", BGFX_CONFIG_RENDERER_OPENGL >= 31, true }, { "EXT_blend_minmax", BGFX_CONFIG_RENDERER_OPENGL >= 14, true }, { "EXT_blend_subtract", BGFX_CONFIG_RENDERER_OPENGL >= 14, true }, { "EXT_color_buffer_half_float", false, true }, // GLES2 extension. { "EXT_color_buffer_float", false, true }, // GLES2 extension. { "EXT_copy_image", false, true }, // GLES2 extension. { "EXT_compressed_ETC1_RGB8_sub_texture", false, true }, // GLES2 extension. { "EXT_debug_label", false, true }, { "EXT_debug_marker", false, true }, { "EXT_debug_tool", false, true }, // RenderDoc extension. { "EXT_discard_framebuffer", false, true }, // GLES2 extension. { "EXT_disjoint_timer_query", false, true }, // GLES2 extension. { "EXT_draw_buffers", false, true }, // GLES2 extension. { "EXT_draw_instanced", false, true }, // GLES2 extension. { "EXT_instanced_arrays", false, true }, // GLES2 extension. { "EXT_frag_depth", false, true }, // GLES2 extension. { "EXT_framebuffer_blit", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "EXT_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "EXT_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "EXT_gpu_shader4", false, true }, { "EXT_multi_draw_indirect", false, true }, // GLES3.1 extension. { "EXT_occlusion_query_boolean", false, true }, // GLES2 extension. { "EXT_packed_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "EXT_read_format_bgra", false, true }, { "EXT_shader_image_load_store", false, true }, { "EXT_shader_texture_lod", false, true }, // GLES2 extension. { "EXT_shadow_samplers", false, true }, { "EXT_sRGB_write_control", false, true }, // GLES2 extension. { "EXT_texture_array", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "EXT_texture_compression_dxt1", false, true }, { "EXT_texture_compression_latc", false, true }, { "EXT_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "EXT_texture_compression_s3tc", false, true }, { "EXT_texture_cube_map_array", false, true }, // GLES3.1 extension. { "EXT_texture_filter_anisotropic", false, true }, { "EXT_texture_format_BGRA8888", false, true }, { "EXT_texture_rg", false, true }, // GLES2 extension. { "EXT_texture_shared_exponent", false, true }, { "EXT_texture_snorm", BGFX_CONFIG_RENDERER_OPENGL >= 30, true }, { "EXT_texture_sRGB", false, true }, { "EXT_texture_storage", false, true }, { "EXT_texture_swizzle", false, true }, { "EXT_texture_type_2_10_10_10_REV", false, true }, { "EXT_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true }, { "EXT_unpack_subimage", false, true }, { "GOOGLE_depth_texture", false, true }, { "IMG_multisampled_render_to_texture", false, true }, { "IMG_read_format", false, true }, { "IMG_shader_binary", false, true }, { "IMG_texture_compression_pvrtc", false, true }, { "IMG_texture_compression_pvrtc2", false, true }, { "IMG_texture_format_BGRA8888", false, true }, { "INTEL_fragment_shader_ordering", false, true }, { "KHR_debug", BGFX_CONFIG_RENDERER_OPENGL >= 43, true }, { "KHR_no_error", false, true }, { "MOZ_WEBGL_compressed_texture_s3tc", false, true }, { "MOZ_WEBGL_depth_texture", false, true }, { "NV_conservative_raster", false, true }, { "NV_copy_image", false, true }, { "NV_draw_buffers", false, true }, // GLES2 extension. { "NV_occlusion_query", false, true }, { "NV_texture_border_clamp", false, true }, // GLES2 extension. { "NVX_gpu_memory_info", false, true }, { "OES_copy_image", false, true }, { "OES_compressed_ETC1_RGB8_texture", false, true }, { "OES_depth24", false, true }, { "OES_depth32", false, true }, { "OES_depth_texture", false, true }, { "OES_element_index_uint", false, true }, { "OES_fragment_precision_high", false, true }, { "OES_get_program_binary", false, true }, { "OES_required_internalformat", false, true }, { "OES_packed_depth_stencil", false, true }, { "OES_read_format", false, true }, { "OES_rgb8_rgba8", false, true }, { "OES_standard_derivatives", false, true }, { "OES_texture_3D", false, true }, { "OES_texture_float", false, true }, { "OES_texture_float_linear", false, true }, { "OES_texture_npot", false, true }, { "OES_texture_half_float", false, true }, { "OES_texture_half_float_linear", false, true }, { "OES_texture_stencil8", false, true }, { "OES_texture_storage_multisample_2d_array", false, true }, { "OES_vertex_array_object", false, !BX_PLATFORM_IOS }, { "OES_vertex_half_float", false, true }, { "OES_vertex_type_10_10_10_2", false, true }, { "WEBGL_color_buffer_float", false, true }, { "WEBGL_compressed_texture_etc1", false, true }, { "WEBGL_compressed_texture_s3tc", false, true }, { "WEBGL_compressed_texture_pvrtc", false, true }, { "WEBGL_depth_texture", false, true }, { "WEBGL_draw_buffers", false, true }, { "WEBKIT_EXT_texture_filter_anisotropic", false, true }, { "WEBKIT_WEBGL_compressed_texture_s3tc", false, true }, { "WEBKIT_WEBGL_depth_texture", false, true }, }; BX_STATIC_ASSERT(Extension::Count == BX_COUNTOF(s_extension) ); static const char* s_ARB_shader_texture_lod[] = { "texture2DLod", "texture2DArrayLod", // BK - interacts with ARB_texture_array. "texture2DProjLod", "texture2DGrad", "texture2DProjGrad", "texture3DLod", "texture3DProjLod", "texture3DGrad", "texture3DProjGrad", "textureCubeLod", "textureCubeGrad", "shadow2DLod", "shadow2DProjLod", NULL // "texture1DLod", // "texture1DProjLod", // "shadow1DLod", // "shadow1DProjLod", }; static const char* s_EXT_shader_texture_lod[] = { "texture2DLod", "texture2DProjLod", "textureCubeLod", "texture2DGrad", "texture2DProjGrad", "textureCubeGrad", NULL }; static const char* s_EXT_shadow_samplers[] = { "shadow2D", "shadow2DProj", NULL }; static const char* s_OES_standard_derivatives[] = { "dFdx", "dFdy", "fwidth", NULL }; static const char* s_uisamplers[] = { "isampler2D", "usampler2D", "isampler3D", "usampler3D", "isamplerCube", "usamplerCube", NULL }; static const char* s_uint[] = { "uint", "uvec2", "uvec3", "uvec4", NULL }; static const char* s_texelFetch[] = { "texture", "textureLod", "textureGrad", "textureProj", "textureProjLod", "texelFetch", "texelFetchOffset", NULL }; static const char* s_texture3D[] = { "sampler3D", "sampler3DArray", NULL }; static const char* s_textureArray[] = { "sampler2DArray", "sampler2DMSArray", "samplerCubeArray", "sampler2DArrayShadow", NULL }; static const char* s_ARB_texture_multisample[] = { "sampler2DMS", "isampler2DMS", "usampler2DMS", NULL }; static const char* s_EXT_gpu_shader4[] = { "gl_VertexID", "gl_InstanceID", "uint", NULL }; static const char* s_ARB_gpu_shader5[] = { "bitfieldReverse", "floatBitsToInt", "floatBitsToUint", "intBitsToFloat", "uintBitsToFloat", NULL }; static const char* s_ARB_shading_language_packing[] = { "packHalf2x16", "unpackHalf2x16", NULL }; static const char* s_intepolationQualifier[] = { "flat", "smooth", "noperspective", "centroid", NULL }; static void GL_APIENTRY stubVertexAttribDivisor(GLuint /*_index*/, GLuint /*_divisor*/) { } static void GL_APIENTRY stubDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei /*_primcount*/) { GL_CHECK(glDrawArrays(_mode, _first, _count) ); } static void GL_APIENTRY stubDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei /*_primcount*/) { GL_CHECK(glDrawElements(_mode, _count, _type, _indices) ); } static void GL_APIENTRY stubInsertEventMarker(GLsizei /*_length*/, const char* /*_marker*/) { } static void GL_APIENTRY stubPushDebugGroup(GLenum /*_source*/, GLuint /*_id*/, GLsizei /*_length*/, const char* /*_message*/) { } static void GL_APIENTRY stubPopDebugGroup() { } static void GL_APIENTRY stubObjectLabel(GLenum /*_identifier*/, GLuint /*_name*/, GLsizei /*_length*/, const char* /*_label*/) { } static void GL_APIENTRY stubInvalidateFramebuffer(GLenum /*_target*/, GLsizei /*_numAttachments*/, const GLenum* /*_attachments*/) { } static void GL_APIENTRY stubMultiDrawArraysIndirect(GLenum _mode, const void* _indirect, GLsizei _drawcount, GLsizei _stride) { const uint8_t* args = (const uint8_t*)_indirect; for (GLsizei ii = 0; ii < _drawcount; ++ii) { GL_CHECK(glDrawArraysIndirect(_mode, (void*)args) ); args += _stride; } } static void GL_APIENTRY stubMultiDrawElementsIndirect(GLenum _mode, GLenum _type, const void* _indirect, GLsizei _drawcount, GLsizei _stride) { const uint8_t* args = (const uint8_t*)_indirect; for (GLsizei ii = 0; ii < _drawcount; ++ii) { GL_CHECK(glDrawElementsIndirect(_mode, _type, (void*)args) ); args += _stride; } } static void GL_APIENTRY stubPolygonMode(GLenum /*_face*/, GLenum /*_mode*/) { } typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height); void flushGlError() { for (GLenum err = glGetError(); err != 0; err = glGetError() ); } GLenum getGlError() { GLenum err = glGetError(); flushGlError(); return err; } static const char* getGLString(GLenum _name) { const char* str = (const char*)glGetString(_name); getGlError(); // ignore error if glGetString returns NULL. if (NULL != str) { return str; } return "<unknown>"; } static uint32_t getGLStringHash(GLenum _name) { const char* str = (const char*)glGetString(_name); getGlError(); // ignore error if glGetString returns NULL. if (NULL != str) { return bx::hash<bx::HashMurmur2A>(str, (uint32_t)bx::strLen(str) ); } return 0; } void dumpExtensions(const char* _extensions) { if (NULL != _extensions) { char name[1024]; const char* pos = _extensions; const char* end = _extensions + bx::strLen(_extensions); while (pos < end) { uint32_t len; bx::StringView space = bx::strFind(pos, ' '); if (!space.isEmpty() ) { len = bx::uint32_min(sizeof(name), (uint32_t)(space.getPtr() - pos) ); } else { len = bx::uint32_min(sizeof(name), (uint32_t)bx::strLen(pos) ); } bx::strCopy(name, BX_COUNTOF(name), pos, len); name[len] = '\0'; BX_TRACE("\t%s", name); pos += len+1; } } } const char* toString(GLenum _enum) { switch (_enum) { case GL_DEBUG_SOURCE_API: return "API"; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "WinSys"; case GL_DEBUG_SOURCE_SHADER_COMPILER: return "Shader"; case GL_DEBUG_SOURCE_THIRD_PARTY: return "3rdparty"; case GL_DEBUG_SOURCE_APPLICATION: return "Application"; case GL_DEBUG_SOURCE_OTHER: return "Other"; case GL_DEBUG_TYPE_ERROR: return "Error"; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "Deprecated behavior"; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "Undefined behavior"; case GL_DEBUG_TYPE_PORTABILITY: return "Portability"; case GL_DEBUG_TYPE_PERFORMANCE: return "Performance"; case GL_DEBUG_TYPE_OTHER: return "Other"; case GL_DEBUG_SEVERITY_HIGH: return "High"; case GL_DEBUG_SEVERITY_MEDIUM: return "Medium"; case GL_DEBUG_SEVERITY_LOW: return "Low"; case GL_DEBUG_SEVERITY_NOTIFICATION: return "SPAM"; default: break; } return "<unknown>"; } void GL_APIENTRY debugProcCb(GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar* _message, const void* /*_userParam*/) { if (GL_DEBUG_SEVERITY_NOTIFICATION != _severity) { BX_TRACE("src %s, type %s, id %d, severity %s, '%s'" , toString(_source) , toString(_type) , _id , toString(_severity) , _message ); BX_UNUSED(_source, _type, _id, _severity, _message); } } GLint glGet(GLenum _pname) { GLint result = 0; glGetIntegerv(_pname, &result); GLenum err = getGlError(); BX_WARN(0 == err, "glGetIntegerv(0x%04x, ...) failed with GL error: 0x%04x.", _pname, err); return 0 == err ? result : 0; } void setTextureFormat(TextureFormat::Enum _format, GLenum _internalFmt, GLenum _fmt, GLenum _type = GL_ZERO) { TextureFormatInfo& tfi = s_textureFormat[_format]; tfi.m_internalFmt = _internalFmt; tfi.m_fmt = _fmt; tfi.m_type = _type; } static void texSubImage( GLenum _target , GLint _level , GLint _xoffset , GLint _yoffset , GLint _zoffset , GLsizei _width , GLsizei _height , GLsizei _depth , GLenum _format , GLenum _type , const GLvoid* _data ) { if (NULL == _data) { return; } if (_target == GL_TEXTURE_3D || _target == GL_TEXTURE_2D_ARRAY || _target == GL_TEXTURE_CUBE_MAP_ARRAY) { glTexSubImage3D( _target , _level , _xoffset , _yoffset , _zoffset , _width , _height , _depth , _format , _type , _data ); } else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) { } else { BX_UNUSED(_zoffset, _depth); glTexSubImage2D( _target , _level , _xoffset , _yoffset , _width , _height , _format , _type , _data ); } } static void texImage( GLenum _target , uint32_t _msaaQuality , GLint _level , GLint _internalFormat , GLsizei _width , GLsizei _height , GLsizei _depth , GLint _border , GLenum _format , GLenum _type , const GLvoid* _data ) { if (_target == GL_TEXTURE_3D) { glTexImage3D( _target , _level , _internalFormat , _width , _height , _depth , _border , _format , _type , _data ); } else if (_target == GL_TEXTURE_2D_ARRAY || _target == GL_TEXTURE_CUBE_MAP_ARRAY) { texSubImage( _target , _level , 0 , 0 , _depth , _width , _height , 1 , _format , _type , _data ); } else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) { } else if (_target == GL_TEXTURE_2D_MULTISAMPLE) { glTexImage2DMultisample( _target , _msaaQuality , _internalFormat , _width , _height , false ); } else { glTexImage2D( _target , _level , _internalFormat , _width , _height , _border , _format , _type , _data ); } BX_UNUSED(_msaaQuality, _depth, _border, _data); } static void compressedTexSubImage( GLenum _target , GLint _level , GLint _xoffset , GLint _yoffset , GLint _zoffset , GLsizei _width , GLsizei _height , GLsizei _depth , GLenum _format , GLsizei _imageSize , const GLvoid* _data ) { if (_target == GL_TEXTURE_3D || _target == GL_TEXTURE_2D_ARRAY) { glCompressedTexSubImage3D( _target , _level , _xoffset , _yoffset , _zoffset , _width , _height , _depth , _format , _imageSize , _data ); } else { BX_UNUSED(_zoffset, _depth); glCompressedTexSubImage2D( _target , _level , _xoffset , _yoffset , _width , _height , _format , _imageSize , _data ); } } static void compressedTexImage( GLenum _target , GLint _level , GLenum _internalformat , GLsizei _width , GLsizei _height , GLsizei _depth , GLint _border , GLsizei _imageSize , const GLvoid* _data ) { if (_target == GL_TEXTURE_3D) { glCompressedTexImage3D( _target , _level , _internalformat , _width , _height , _depth , _border , _imageSize , _data ); } else if (_target == GL_TEXTURE_2D_ARRAY || _target == GL_TEXTURE_CUBE_MAP_ARRAY) { compressedTexSubImage( _target , _level , 0 , 0 , _depth , _width , _height , 1 , _internalformat , _imageSize , _data ); } else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) { } else { BX_UNUSED(_depth); glCompressedTexImage2D( _target , _level , _internalformat , _width , _height , _border , _imageSize , _data ); } } GLenum initTestTexture(TextureFormat::Enum _format, bool _srgb, bool _mipmaps, bool _array, GLsizei _dim) { const TextureFormatInfo& tfi = s_textureFormat[_format]; GLenum internalFmt = _srgb ? tfi.m_internalFmtSrgb : tfi.m_internalFmt ; GLsizei bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(_format) ); GLsizei size = (_dim*_dim*bpp)/8; void* data = NULL; if (bimg::isDepth(bimg::TextureFormat::Enum(_format) ) ) { _srgb = false; _mipmaps = false; _array = false; } else { data = bx::alignPtr(alloca(size+16), 0, 16); } flushGlError(); GLenum err = 0; const GLenum target = _array ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D ; if (bimg::isCompressed(bimg::TextureFormat::Enum(_format) ) ) { for (uint32_t ii = 0, dim = _dim; ii < (_mipmaps ? 5u : 1u) && 0 == err; ++ii, dim >>= 1) { dim = bx::uint32_max(1, dim); uint32_t block = bx::uint32_max(4, dim); size = (block*block*bpp)/8; compressedTexImage(target, ii, internalFmt, dim, dim, 0, 0, size, data); err |= getGlError(); } } else { for (uint32_t ii = 0, dim = _dim; ii < (_mipmaps ? 5u : 1u) && 0 == err; ++ii, dim >>= 1) { dim = bx::uint32_max(1, dim); size = (dim*dim*bpp)/8; texImage(target, 0, ii, internalFmt, dim, dim, 0, 0, tfi.m_fmt, tfi.m_type, data); err |= getGlError(); } } return err; } static bool isTextureFormatValid( TextureFormat::Enum _format , bool _srgb = false , bool _mipAutogen = false , bool _array = false , GLsizei _dim = 16 ) { const TextureFormatInfo& tfi = s_textureFormat[_format]; GLenum internalFmt = _srgb ? tfi.m_internalFmtSrgb : tfi.m_internalFmt ; if (GL_ZERO == internalFmt) { return false; } BX_TRACE("%d, %d, %d, %s", _array, _srgb, _mipAutogen, getName(_format) ); const GLenum target = _array ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D ; GLuint id; GL_CHECK(glGenTextures(1, &id) ); GL_CHECK(glBindTexture(target, id) ); GLenum err = 0; if (_array) { glTexStorage3D(target , 1 + GLsizei(bx::log2(float(_dim) ) ) , internalFmt , _dim , _dim , _dim ); err = getGlError(); } if (0 == err) { err = initTestTexture(_format, _srgb, _mipAutogen, _array, _dim); BX_WARN(0 == err, "TextureFormat::%s %s%s%sis not supported (%x: %s)." , getName(_format) , _srgb ? "+sRGB " : "" , _mipAutogen ? "+mipAutoGen " : "" , _array ? "+array " : "" , err , glEnumName(err) ); if (0 == err && _mipAutogen) { glGenerateMipmap(target); err = getGlError(); } } GL_CHECK(glDeleteTextures(1, &id) ); return 0 == err; } static bool isImageFormatValid(TextureFormat::Enum _format, GLsizei _dim = 16) { if (GL_ZERO == s_imageFormat[_format]) { return false; } GLuint id; GL_CHECK(glGenTextures(1, &id) ); GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) ); flushGlError(); GLenum err = 0; glTexStorage2D(GL_TEXTURE_2D, 1, s_imageFormat[_format], _dim, _dim); err |= getGlError(); if (0 == err) { glBindImageTexture(0 , id , 0 , GL_FALSE , 0 , GL_READ_WRITE , s_imageFormat[_format] ); err |= getGlError(); } GL_CHECK(glDeleteTextures(1, &id) ); return 0 == err; } static bool isFramebufferFormatValid( TextureFormat::Enum _format , bool _srgb = false , bool _writeOnly = false , GLsizei _dim = 16 ) { const TextureFormatInfo& tfi = s_textureFormat[_format]; GLenum internalFmt = _srgb ? tfi.m_internalFmtSrgb : tfi.m_internalFmt ; if (GL_ZERO == internalFmt) { return false; } if (_writeOnly) { GLuint rbo; glGenRenderbuffers(1, &rbo); glBindRenderbuffer(GL_RENDERBUFFER, rbo); glRenderbufferStorage(GL_RENDERBUFFER , s_rboFormat[_format] , _dim , _dim ); glBindRenderbuffer(GL_RENDERBUFFER, 0); glDeleteRenderbuffers(1, &rbo); GLenum err = getGlError(); return 0 == err; } GLuint fbo; GL_CHECK(glGenFramebuffers(1, &fbo) ); GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, fbo) ); GLuint id; GL_CHECK(glGenTextures(1, &id) ); GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) ); GLenum err = initTestTexture(_format, _srgb, false, false, _dim); GLenum attachment; if (bimg::isDepth(bimg::TextureFormat::Enum(_format) ) ) { const bimg::ImageBlockInfo& info = bimg::getBlockInfo(bimg::TextureFormat::Enum(_format) ); if (0 == info.depthBits) { attachment = GL_STENCIL_ATTACHMENT; } else if (0 == info.stencilBits) { attachment = GL_DEPTH_ATTACHMENT; } else { attachment = GL_DEPTH_STENCIL_ATTACHMENT; } } else { attachment = GL_COLOR_ATTACHMENT0; } glFramebufferTexture2D(GL_FRAMEBUFFER , attachment , GL_TEXTURE_2D , id , 0 ); err = getGlError(); if (0 == err) { err = glCheckFramebufferStatus(GL_FRAMEBUFFER); } GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) ); GL_CHECK(glDeleteFramebuffers(1, &fbo) ); GL_CHECK(glDeleteTextures(1, &id) ); return GL_FRAMEBUFFER_COMPLETE == err; } static void getFilters(uint32_t _flags, bool _hasMips, GLenum& _magFilter, GLenum& _minFilter) { const uint32_t mag = (_flags&BGFX_SAMPLER_MAG_MASK)>>BGFX_SAMPLER_MAG_SHIFT; const uint32_t min = (_flags&BGFX_SAMPLER_MIN_MASK)>>BGFX_SAMPLER_MIN_SHIFT; const uint32_t mip = (_flags&BGFX_SAMPLER_MIP_MASK)>>BGFX_SAMPLER_MIP_SHIFT; _magFilter = s_textureFilterMag[mag]; _minFilter = s_textureFilterMin[min][_hasMips ? mip+1 : 0]; } void updateExtension(const bx::StringView& _name) { bx::StringView ext(_name); if (0 == bx::strCmp(ext, "GL_", 3) ) // skip GL_ { ext.set(ext.getPtr()+3, ext.getTerm() ); } bool supported = false; for (uint32_t ii = 0; ii < Extension::Count; ++ii) { Extension& extension = s_extension[ii]; if (!extension.m_supported && extension.m_initialize) { if (0 == bx::strCmp(ext, extension.m_name) ) { extension.m_supported = true; supported = true; break; } } } BX_TRACE("GL_EXTENSION %s: %.*s", supported ? " (supported)" : "", _name.getLength(), _name.getPtr() ); BX_UNUSED(supported); } struct VendorId { const char* name; uint16_t id; }; static const VendorId s_vendorIds[] = { { "NVIDIA Corporation", BGFX_PCI_ID_NVIDIA }, { "Advanced Micro Devices, Inc.", BGFX_PCI_ID_AMD }, { "Intel", BGFX_PCI_ID_INTEL }, { "ATI Technologies Inc.", BGFX_PCI_ID_AMD }, }; struct Workaround { void reset() { m_detachShader = true; } bool m_detachShader; }; struct RendererContextGL : public RendererContextI { RendererContextGL() : m_numWindows(1) , m_rtMsaa(false) , m_fbDiscard(BGFX_CLEAR_NONE) , m_capture(NULL) , m_captureSize(0) , m_maxAnisotropy(0.0f) , m_maxAnisotropyDefault(0.0f) , m_maxMsaa(0) , m_vao(0) , m_blitSupported(false) , m_readBackSupported(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) ) , m_vaoSupport(false) , m_samplerObjectSupport(false) , m_shadowSamplersSupport(false) , m_srgbWriteControlSupport(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) ) , m_borderColorSupport(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) ) , m_programBinarySupport(false) , m_textureSwizzleSupport(false) , m_depthTextureSupport(false) , m_timerQuerySupport(false) , m_occlusionQuerySupport(false) , m_atocSupport(false) , m_conservativeRasterSupport(false) , m_flip(false) , m_hash( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT) , m_backBufferFbo(0) , m_msaaBackBufferFbo(0) , m_clearQuadColor(BGFX_INVALID_HANDLE) , m_clearQuadDepth(BGFX_INVALID_HANDLE) { bx::memSet(m_msaaBackBufferRbos, 0, sizeof(m_msaaBackBufferRbos) ); } ~RendererContextGL() { } bool init(const Init& _init) { struct ErrorState { enum Enum { Default, }; }; ErrorState::Enum errorState = ErrorState::Default; if (_init.debug || _init.profile) { m_renderdocdll = loadRenderDoc(); } m_fbh.idx = kInvalidHandle; bx::memSet(m_uniforms, 0, sizeof(m_uniforms) ); bx::memSet(&m_resolution, 0, sizeof(m_resolution) ); setRenderContextSize(_init.resolution.width, _init.resolution.height); m_vendor = getGLString(GL_VENDOR); m_renderer = getGLString(GL_RENDERER); m_version = getGLString(GL_VERSION); m_glslVersion = getGLString(GL_SHADING_LANGUAGE_VERSION); for (uint32_t ii = 0; ii < BX_COUNTOF(s_vendorIds); ++ii) { const VendorId& vendorId = s_vendorIds[ii]; if (0 == bx::strCmp(vendorId.name, m_vendor, bx::strLen(vendorId.name) ) ) { g_caps.vendorId = vendorId.id; break; } } m_workaround.reset(); GLint numCmpFormats = 0; GL_CHECK(glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numCmpFormats) ); BX_TRACE("GL_NUM_COMPRESSED_TEXTURE_FORMATS %d", numCmpFormats); GLint* cmpFormat = NULL; if (0 < numCmpFormats) { numCmpFormats = numCmpFormats > 256 ? 256 : numCmpFormats; cmpFormat = (GLint*)alloca(sizeof(GLint)*numCmpFormats); GL_CHECK(glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, cmpFormat) ); for (GLint ii = 0; ii < numCmpFormats; ++ii) { GLint internalFmt = cmpFormat[ii]; uint32_t fmt = uint32_t(TextureFormat::Unknown); for (uint32_t jj = 0; jj < fmt; ++jj) { if (s_textureFormat[jj].m_internalFmt == (GLenum)internalFmt) { s_textureFormat[jj].m_supported = true; fmt = jj; } } BX_TRACE(" %3d: %8x %s", ii, internalFmt, getName( (TextureFormat::Enum)fmt) ); } } if (BX_ENABLED(BGFX_CONFIG_DEBUG) ) { #define GL_GET(_pname, _min) BX_TRACE(" " #_pname " %d (min: %d)", glGet(_pname), _min) BX_TRACE("Defaults:"); #if BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES GL_GET(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 16); GL_GET(GL_MAX_VERTEX_UNIFORM_VECTORS, 128); GL_GET(GL_MAX_VARYING_VECTORS, 8); #else GL_GET(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, 16 * 4); GL_GET(GL_MAX_VERTEX_UNIFORM_COMPONENTS, 128 * 4); GL_GET(GL_MAX_VARYING_FLOATS, 8 * 4); #endif // BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES GL_GET(GL_MAX_VERTEX_ATTRIBS, 8); GL_GET(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 8); GL_GET(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 16); GL_GET(GL_MAX_TEXTURE_IMAGE_UNITS, 8); GL_GET(GL_MAX_TEXTURE_SIZE, 64); GL_GET(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0); GL_GET(GL_MAX_RENDERBUFFER_SIZE, 1); GL_GET(GL_MAX_COLOR_ATTACHMENTS, 1); GL_GET(GL_MAX_DRAW_BUFFERS, 1); GL_GET(GL_MAX_LABEL_LENGTH, 0); #undef GL_GET BX_TRACE(" Vendor: %s", m_vendor); BX_TRACE(" Renderer: %s", m_renderer); BX_TRACE(" Version: %s", m_version); BX_TRACE("GLSL version: %s", m_glslVersion); } // Initial binary shader hash depends on driver version. m_hash = ( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT) ^ (uint64_t(getGLStringHash(GL_VENDOR ) )<<32) ^ (uint64_t(getGLStringHash(GL_RENDERER) )<<0 ) ^ (uint64_t(getGLStringHash(GL_VERSION ) )<<16) ; if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) && 0 == bx::strCmp(m_vendor, "Imagination Technologies") && !bx::strFind(m_version, "(SDK 3.5@3510720)").isEmpty() ) { // Skip initializing extensions that are broken in emulator. s_extension[Extension::ARB_program_interface_query ].m_initialize = s_extension[Extension::ARB_shader_storage_buffer_object].m_initialize = false; } if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) && 0 == bx::strCmp(m_vendor, "Imagination Technologies") && !bx::strFind(m_version, "1.8@905891").isEmpty() ) { m_workaround.m_detachShader = false; } if (BX_ENABLED(BGFX_CONFIG_RENDERER_USE_EXTENSIONS) ) { const char* extensions = (const char*)glGetString(GL_EXTENSIONS); getGlError(); // ignore error if glGetString returns NULL. if (NULL != extensions) { bx::StringView ext(extensions); uint32_t index = 0; while (!ext.isEmpty() ) { const bx::StringView space = bx::strFind(ext, ' '); const bx::StringView token = bx::StringView(ext.getPtr(), space.getPtr() ); updateExtension(token); ext.set(space.getPtr() + (space.isEmpty() ? 0 : 1), ext.getTerm() ); ++index; } } else if (NULL != glGetStringi) { GLint numExtensions = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions); getGlError(); // ignore error if glGetIntegerv returns NULL. for (GLint index = 0; index < numExtensions; ++index) { const char* name = (const char*)glGetStringi(GL_EXTENSIONS, index); updateExtension(name); } } BX_TRACE("Supported extensions:"); for (uint32_t ii = 0; ii < Extension::Count; ++ii) { if (s_extension[ii].m_supported) { BX_TRACE("\t%2d: %s", ii, s_extension[ii].m_name); } } } if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && !s_extension[Extension::ARB_framebuffer_object].m_supported) { BX_TRACE("Init error: ARB_framebuffer_object not supported."); goto error; } { // Allow all texture filters. bx::memSet(s_textureFilter, true, BX_COUNTOF(s_textureFilter) ); bool bc123Supported = 0 || s_extension[Extension::EXT_texture_compression_s3tc ].m_supported || s_extension[Extension::MOZ_WEBGL_compressed_texture_s3tc ].m_supported || s_extension[Extension::WEBGL_compressed_texture_s3tc ].m_supported || s_extension[Extension::WEBKIT_WEBGL_compressed_texture_s3tc].m_supported ; s_textureFormat[TextureFormat::BC1].m_supported |= bc123Supported || s_extension[Extension::ANGLE_texture_compression_dxt1].m_supported || s_extension[Extension::EXT_texture_compression_dxt1 ].m_supported ; if (!s_textureFormat[TextureFormat::BC1].m_supported && ( s_textureFormat[TextureFormat::BC2].m_supported || s_textureFormat[TextureFormat::BC3].m_supported) ) { // If RGBA_S3TC_DXT1 is not supported, maybe RGB_S3TC_DXT1 is? for (GLint ii = 0; ii < numCmpFormats; ++ii) { if (GL_COMPRESSED_RGB_S3TC_DXT1_EXT == cmpFormat[ii]) { setTextureFormat(TextureFormat::BC1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_RGB_S3TC_DXT1_EXT); s_textureFormat[TextureFormat::BC1].m_supported = true; break; } } } s_textureFormat[TextureFormat::BC2].m_supported |= bc123Supported || s_extension[Extension::ANGLE_texture_compression_dxt3 ].m_supported || s_extension[Extension::CHROMIUM_texture_compression_dxt3].m_supported ; s_textureFormat[TextureFormat::BC3].m_supported |= bc123Supported || s_extension[Extension::ANGLE_texture_compression_dxt5 ].m_supported || s_extension[Extension::CHROMIUM_texture_compression_dxt5].m_supported ; if (s_extension[Extension::EXT_texture_compression_latc].m_supported) { setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_COMPRESSED_LUMINANCE_LATC1_EXT); setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT); } if (s_extension[Extension::ARB_texture_compression_rgtc].m_supported || s_extension[Extension::EXT_texture_compression_rgtc].m_supported) { setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1); setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2); } bool etc1Supported = 0 || s_extension[Extension::OES_compressed_ETC1_RGB8_texture].m_supported || s_extension[Extension::WEBGL_compressed_texture_etc1 ].m_supported ; s_textureFormat[TextureFormat::ETC1].m_supported |= etc1Supported; bool etc2Supported = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::ARB_ES3_compatibility].m_supported ; s_textureFormat[TextureFormat::ETC2 ].m_supported |= etc2Supported; s_textureFormat[TextureFormat::ETC2A ].m_supported |= etc2Supported; s_textureFormat[TextureFormat::ETC2A1].m_supported |= etc2Supported; if (!s_textureFormat[TextureFormat::ETC1].m_supported && s_textureFormat[TextureFormat::ETC2].m_supported) { // When ETC2 is supported override ETC1 texture format settings. s_textureFormat[TextureFormat::ETC1].m_internalFmt = GL_COMPRESSED_RGB8_ETC2; s_textureFormat[TextureFormat::ETC1].m_fmt = GL_COMPRESSED_RGB8_ETC2; s_textureFormat[TextureFormat::ETC1].m_supported = true; } bool ptc1Supported = 0 || s_extension[Extension::IMG_texture_compression_pvrtc ].m_supported || s_extension[Extension::WEBGL_compressed_texture_pvrtc].m_supported ; s_textureFormat[TextureFormat::PTC12 ].m_supported |= ptc1Supported; s_textureFormat[TextureFormat::PTC14 ].m_supported |= ptc1Supported; s_textureFormat[TextureFormat::PTC12A].m_supported |= ptc1Supported; s_textureFormat[TextureFormat::PTC14A].m_supported |= ptc1Supported; bool ptc2Supported = s_extension[Extension::IMG_texture_compression_pvrtc2].m_supported; s_textureFormat[TextureFormat::PTC22].m_supported |= ptc2Supported; s_textureFormat[TextureFormat::PTC24].m_supported |= ptc2Supported; if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) ) { setTextureFormat(TextureFormat::D32, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT); if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) ) { setTextureFormat(TextureFormat::RGBA16F, GL_RGBA, GL_RGBA, GL_HALF_FLOAT); setTextureFormat(TextureFormat::RGBA32F, GL_RGBA, GL_RGBA, GL_FLOAT); // internalFormat and format must match: // https://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexImage2D.xml setTextureFormat(TextureFormat::RGBA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE); setTextureFormat(TextureFormat::R5G6B5, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5_REV); setTextureFormat(TextureFormat::RGBA4, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV); setTextureFormat(TextureFormat::RGB5A1, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV); if (s_extension[Extension::OES_texture_half_float].m_supported || s_extension[Extension::OES_texture_float ].m_supported) { // https://www.khronos.org/registry/gles/extensions/OES/OES_texture_float.txt // When half/float is available via extensions texture will be marked as // incomplete if it uses anything other than nearest filter. const bool linear16F = s_extension[Extension::OES_texture_half_float_linear].m_supported; const bool linear32F = s_extension[Extension::OES_texture_float_linear ].m_supported; s_textureFilter[TextureFormat::R16F] = linear16F; s_textureFilter[TextureFormat::RG16F] = linear16F; s_textureFilter[TextureFormat::RGBA16F] = linear16F; s_textureFilter[TextureFormat::R32F] = linear32F; s_textureFilter[TextureFormat::RG32F] = linear32F; s_textureFilter[TextureFormat::RGBA32F] = linear32F; } if (BX_ENABLED(BX_PLATFORM_IOS) || BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)) { setTextureFormat(TextureFormat::D16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT); setTextureFormat(TextureFormat::D24S8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8); } } } if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) ) { setTextureFormat(TextureFormat::R8I, GL_R8I, GL_RED_INTEGER, GL_BYTE); setTextureFormat(TextureFormat::R8U, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE); setTextureFormat(TextureFormat::R16I, GL_R16I, GL_RED_INTEGER, GL_SHORT); setTextureFormat(TextureFormat::R16U, GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT); // setTextureFormat(TextureFormat::RG16, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT); // setTextureFormat(TextureFormat::RGBA16, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT); setTextureFormat(TextureFormat::R32U, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT); setTextureFormat(TextureFormat::RG32U, GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT); setTextureFormat(TextureFormat::RGBA32U, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT); } if (s_extension[Extension::EXT_texture_format_BGRA8888 ].m_supported || s_extension[Extension::EXT_bgra ].m_supported || s_extension[Extension::IMG_texture_format_BGRA8888 ].m_supported || s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported) { if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) ) { m_readPixelsFmt = GL_BGRA; } // Mixing GLES and GL extensions here. OpenGL EXT_bgra and // APPLE_texture_format_BGRA8888 wants // format to be BGRA but internal format to stay RGBA, but // EXT_texture_format_BGRA8888 wants both format and internal // format to be BGRA. // // Reference(s): // - https://web.archive.org/web/20181126035829/https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_format_BGRA8888.txt // - https://web.archive.org/web/20181126035841/https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_bgra.txt // - https://web.archive.org/web/20181126035851/https://www.khronos.org/registry/OpenGL/extensions/APPLE/APPLE_texture_format_BGRA8888.txt // if (!s_extension[Extension::EXT_bgra ].m_supported && !s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported) { s_textureFormat[TextureFormat::BGRA8].m_internalFmt = GL_BGRA; } if (!isTextureFormatValid(TextureFormat::BGRA8) ) { // Revert back to RGBA if texture can't be created. setTextureFormat(TextureFormat::BGRA8, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE); } } if (BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) ) { setTextureFormat(TextureFormat::RGBA4, GL_ZERO, GL_ZERO, GL_ZERO); setTextureFormat(TextureFormat::RGB5A1, GL_ZERO, GL_ZERO, GL_ZERO); if (!isTextureFormatValid(TextureFormat::R8) ) { // GL core has to use GL_R8 Issue#208, GLES2 has to use GL_LUMINANCE issue#226 s_textureFormat[TextureFormat::R8].m_internalFmt = GL_LUMINANCE; s_textureFormat[TextureFormat::R8].m_fmt = GL_LUMINANCE; } } for (uint32_t ii = BX_ENABLED(BX_PLATFORM_IOS) ? TextureFormat::Unknown : 0 // skip test on iOS! ; ii < TextureFormat::Count ; ++ii ) { if (TextureFormat::Unknown != ii && TextureFormat::UnknownDepth != ii) { s_textureFormat[ii].m_supported = isTextureFormatValid(TextureFormat::Enum(ii) ); } } if (BX_ENABLED(0) ) { // Disable all compressed texture formats. For testing only. for (uint32_t ii = 0; ii < TextureFormat::Unknown; ++ii) { s_textureFormat[ii].m_supported = false; } } const bool computeSupport = false || !!(BGFX_CONFIG_RENDERER_OPENGLES >= 31) || s_extension[Extension::ARB_compute_shader].m_supported ; for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii) { const TextureFormat::Enum fmt = TextureFormat::Enum(ii); uint16_t supported = BGFX_CAPS_FORMAT_TEXTURE_NONE; supported |= s_textureFormat[ii].m_supported ? BGFX_CAPS_FORMAT_TEXTURE_2D | BGFX_CAPS_FORMAT_TEXTURE_3D | BGFX_CAPS_FORMAT_TEXTURE_CUBE : BGFX_CAPS_FORMAT_TEXTURE_NONE ; supported |= isTextureFormatValid(fmt, true) ? BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB : BGFX_CAPS_FORMAT_TEXTURE_NONE ; if (!bimg::isCompressed(bimg::TextureFormat::Enum(fmt) ) ) { supported |= isTextureFormatValid(fmt, false, true) ? BGFX_CAPS_FORMAT_TEXTURE_MIP_AUTOGEN : BGFX_CAPS_FORMAT_TEXTURE_NONE ; } supported |= computeSupport && isImageFormatValid(fmt) ? BGFX_CAPS_FORMAT_TEXTURE_IMAGE : BGFX_CAPS_FORMAT_TEXTURE_NONE ; supported |= isFramebufferFormatValid(fmt) ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER : BGFX_CAPS_FORMAT_TEXTURE_NONE ; supported |= isFramebufferFormatValid(fmt, false, true) ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER : BGFX_CAPS_FORMAT_TEXTURE_NONE ; if (NULL != glGetInternalformativ) { GLint maxSamples; glGetInternalformativ(GL_RENDERBUFFER , s_textureFormat[ii].m_internalFmt , GL_SAMPLES , 1 , &maxSamples ); GLenum err = getGlError(); supported |= 0 == err && maxSamples > 0 ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA : BGFX_CAPS_FORMAT_TEXTURE_NONE ; glGetInternalformativ(GL_TEXTURE_2D_MULTISAMPLE , s_textureFormat[ii].m_internalFmt , GL_SAMPLES , 1 , &maxSamples ); err = getGlError(); supported |= 0 == err && maxSamples > 0 ? BGFX_CAPS_FORMAT_TEXTURE_MSAA : BGFX_CAPS_FORMAT_TEXTURE_NONE ; } g_caps.formats[ii] = supported; } g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::OES_texture_3D].m_supported ? BGFX_CAPS_TEXTURE_3D : 0 ; g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::EXT_shadow_samplers].m_supported ? BGFX_CAPS_TEXTURE_COMPARE_ALL : 0 ; g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::OES_vertex_half_float].m_supported ? BGFX_CAPS_VERTEX_ATTRIB_HALF : 0 ; g_caps.supported |= false || s_extension[Extension::ARB_vertex_type_2_10_10_10_rev].m_supported || s_extension[Extension::OES_vertex_type_10_10_10_2].m_supported ? BGFX_CAPS_VERTEX_ATTRIB_UINT10 : 0 ; g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::EXT_frag_depth].m_supported ? BGFX_CAPS_FRAGMENT_DEPTH : 0 ; g_caps.supported |= s_extension[Extension::ARB_draw_buffers_blend].m_supported ? BGFX_CAPS_BLEND_INDEPENDENT : 0 ; g_caps.supported |= s_extension[Extension::INTEL_fragment_shader_ordering].m_supported ? BGFX_CAPS_FRAGMENT_ORDERING : 0 ; g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::OES_element_index_uint].m_supported ? BGFX_CAPS_INDEX32 : 0 ; const bool drawIndirectSupported = false || s_extension[Extension::AMD_multi_draw_indirect].m_supported || s_extension[Extension::ARB_draw_indirect ].m_supported || s_extension[Extension::ARB_multi_draw_indirect].m_supported || s_extension[Extension::EXT_multi_draw_indirect].m_supported ; if (drawIndirectSupported) { if (NULL == glMultiDrawArraysIndirect || NULL == glMultiDrawElementsIndirect) { glMultiDrawArraysIndirect = stubMultiDrawArraysIndirect; glMultiDrawElementsIndirect = stubMultiDrawElementsIndirect; } } g_caps.supported |= drawIndirectSupported ? BGFX_CAPS_DRAW_INDIRECT : 0 ; if (BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) || NULL == glPolygonMode) { glPolygonMode = stubPolygonMode; } if (s_extension[Extension::ARB_copy_image].m_supported || s_extension[Extension::EXT_copy_image].m_supported || s_extension[Extension:: NV_copy_image].m_supported || s_extension[Extension::OES_copy_image].m_supported) { m_blitSupported = NULL != glCopyImageSubData; g_caps.supported |= m_blitSupported ? BGFX_CAPS_TEXTURE_BLIT : 0 ; } g_caps.supported |= m_readBackSupported ? BGFX_CAPS_TEXTURE_READ_BACK : 0 ; g_caps.supported |= false || s_extension[Extension::EXT_texture_array].m_supported || s_extension[Extension::EXT_gpu_shader4].m_supported || (!!(BGFX_CONFIG_RENDERER_OPENGLES >= 30) && !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) ) ? BGFX_CAPS_TEXTURE_2D_ARRAY : 0 ; g_caps.supported |= false || s_extension[Extension::EXT_gpu_shader4].m_supported || (!!(BGFX_CONFIG_RENDERER_OPENGLES >= 30) && !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) ) ? BGFX_CAPS_VERTEX_ID : 0 ; g_caps.supported |= false || s_extension[Extension::ARB_texture_cube_map_array].m_supported || s_extension[Extension::EXT_texture_cube_map_array].m_supported ? BGFX_CAPS_TEXTURE_CUBE_ARRAY : 0 ; g_caps.limits.maxTextureSize = uint16_t(glGet(GL_MAX_TEXTURE_SIZE) ); g_caps.limits.maxTextureLayers = uint16_t(bx::max(glGet(GL_MAX_ARRAY_TEXTURE_LAYERS), 1) ); g_caps.limits.maxComputeBindings = computeSupport ? BGFX_MAX_COMPUTE_BINDINGS : 0; g_caps.limits.maxVertexStreams = BGFX_CONFIG_MAX_VERTEX_STREAMS; if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::EXT_draw_buffers ].m_supported || s_extension[Extension::WEBGL_draw_buffers].m_supported) { g_caps.limits.maxFBAttachments = uint8_t(bx::uint32_clamp( glGet(GL_MAX_DRAW_BUFFERS) , 1 , BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS) ); } // if (s_extension[Extension::ARB_clip_control].m_supported) // { // GL_CHECK(glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE) ); // g_caps.originBottomLeft = true; // } // else { g_caps.homogeneousDepth = true; g_caps.originBottomLeft = true; } m_vaoSupport = !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) && (!!(BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::ARB_vertex_array_object].m_supported || s_extension[Extension::OES_vertex_array_object].m_supported ); if (m_vaoSupport) { GL_CHECK(glGenVertexArrays(1, &m_vao) ); } m_samplerObjectSupport = !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) && (!!(BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::ARB_sampler_objects].m_supported ); m_shadowSamplersSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::EXT_shadow_samplers].m_supported ; m_programBinarySupport = !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) && (!!(BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::ARB_get_program_binary].m_supported || s_extension[Extension::OES_get_program_binary].m_supported || s_extension[Extension::IMG_shader_binary ].m_supported ); m_textureSwizzleSupport = false || s_extension[Extension::ARB_texture_swizzle].m_supported || s_extension[Extension::EXT_texture_swizzle].m_supported ; m_depthTextureSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::ANGLE_depth_texture ].m_supported || s_extension[Extension::CHROMIUM_depth_texture ].m_supported || s_extension[Extension::GOOGLE_depth_texture ].m_supported || s_extension[Extension::OES_depth_texture ].m_supported || s_extension[Extension::MOZ_WEBGL_depth_texture ].m_supported || s_extension[Extension::WEBGL_depth_texture ].m_supported || s_extension[Extension::WEBKIT_WEBGL_depth_texture].m_supported ; m_timerQuerySupport = false || s_extension[Extension::ANGLE_timer_query ].m_supported || s_extension[Extension::ARB_timer_query ].m_supported || s_extension[Extension::EXT_disjoint_timer_query].m_supported || s_extension[Extension::EXT_timer_query ].m_supported ; m_timerQuerySupport &= true && NULL != glQueryCounter && NULL != glGetQueryObjectiv && NULL != glGetQueryObjectui64v ; m_occlusionQuerySupport = false || s_extension[Extension::ARB_occlusion_query ].m_supported || s_extension[Extension::ARB_occlusion_query2 ].m_supported || s_extension[Extension::EXT_occlusion_query_boolean].m_supported || s_extension[Extension::NV_occlusion_query ].m_supported ; m_occlusionQuerySupport &= true && NULL != glGenQueries && NULL != glDeleteQueries && NULL != glBeginQuery && NULL != glEndQuery ; m_atocSupport = s_extension[Extension::ARB_multisample].m_supported; m_conservativeRasterSupport = s_extension[Extension::NV_conservative_raster].m_supported; m_imageLoadStoreSupport = false || s_extension[Extension::ARB_shader_image_load_store].m_supported || s_extension[Extension::EXT_shader_image_load_store].m_supported ; g_caps.supported |= 0 | (m_atocSupport ? BGFX_CAPS_ALPHA_TO_COVERAGE : 0) | (m_conservativeRasterSupport ? BGFX_CAPS_CONSERVATIVE_RASTER : 0) | (m_occlusionQuerySupport ? BGFX_CAPS_OCCLUSION_QUERY : 0) | (m_depthTextureSupport ? BGFX_CAPS_TEXTURE_COMPARE_LEQUAL : 0) | (computeSupport ? BGFX_CAPS_COMPUTE : 0) | (m_imageLoadStoreSupport ? BGFX_CAPS_FRAMEBUFFER_RW : 0) ; g_caps.supported |= m_glctx.getCaps(); if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) ) { m_srgbWriteControlSupport = s_extension[Extension::EXT_sRGB_write_control].m_supported; m_borderColorSupport = s_extension[Extension::NV_texture_border_clamp].m_supported; s_textureAddress[BGFX_SAMPLER_U_BORDER>>BGFX_SAMPLER_U_SHIFT] = s_extension[Extension::NV_texture_border_clamp].m_supported ? GL_CLAMP_TO_BORDER : GL_CLAMP_TO_EDGE ; } if (s_extension[Extension::EXT_texture_filter_anisotropic].m_supported) { GL_CHECK(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &m_maxAnisotropyDefault) ); } if (s_extension[Extension::ARB_texture_multisample].m_supported || s_extension[Extension::ANGLE_framebuffer_multisample].m_supported) { GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES, &m_maxMsaa) ); } if (s_extension[Extension::OES_read_format].m_supported && (s_extension[Extension::IMG_read_format].m_supported || s_extension[Extension::EXT_read_format_bgra].m_supported) ) { m_readPixelsFmt = GL_BGRA; } else { m_readPixelsFmt = GL_RGBA; } if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) ) { g_caps.supported |= BGFX_CAPS_INSTANCING; } else { if (s_extension[Extension::ANGLE_instanced_arrays].m_supported || s_extension[Extension::ARB_instanced_arrays].m_supported || s_extension[Extension::EXT_instanced_arrays].m_supported) { if (NULL != glVertexAttribDivisor && NULL != glDrawArraysInstanced && NULL != glDrawElementsInstanced) { g_caps.supported |= BGFX_CAPS_INSTANCING; } } if (0 == (g_caps.supported & BGFX_CAPS_INSTANCING) ) { glVertexAttribDivisor = stubVertexAttribDivisor; glDrawArraysInstanced = stubDrawArraysInstanced; glDrawElementsInstanced = stubDrawElementsInstanced; } } if (s_extension[Extension::ARB_debug_output].m_supported || s_extension[Extension::KHR_debug].m_supported) { if (NULL != glDebugMessageControl && NULL != glDebugMessageInsert && NULL != glDebugMessageCallback && NULL != glGetDebugMessageLog) { GL_CHECK(glDebugMessageCallback(debugProcCb, NULL) ); GL_CHECK(glDebugMessageControl(GL_DONT_CARE , GL_DONT_CARE , GL_DEBUG_SEVERITY_MEDIUM , 0 , NULL , GL_TRUE ) ); } } if (NULL == glPushDebugGroup || NULL == glPopDebugGroup) { glPushDebugGroup = stubPushDebugGroup; glPopDebugGroup = stubPopDebugGroup; } if (s_extension[Extension::ARB_seamless_cube_map].m_supported) { GL_CHECK(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS) ); } if (NULL == glInsertEventMarker || !s_extension[Extension::EXT_debug_marker].m_supported) { glInsertEventMarker = stubInsertEventMarker; } m_maxLabelLen = uint16_t(glGet(GL_MAX_LABEL_LENGTH) ); setGraphicsDebuggerPresent(s_extension[Extension::EXT_debug_tool].m_supported); if (NULL == glObjectLabel) { glObjectLabel = stubObjectLabel; } if (NULL == glInvalidateFramebuffer) { glInvalidateFramebuffer = stubInvalidateFramebuffer; } if (m_timerQuerySupport) { m_gpuTimer.create(); } if (m_occlusionQuerySupport) { m_occlusionQuery.create(); } // Init reserved part of view name. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii) { bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1, "%3d ", ii); } m_needPresent = false; } return true; error: switch (errorState) { case ErrorState::Default: break; } m_glctx.destroy(); unloadRenderDoc(m_renderdocdll); return false; } void shutdown() { if (m_vaoSupport) { GL_CHECK(glBindVertexArray(0) ); GL_CHECK(glDeleteVertexArrays(1, &m_vao) ); m_vao = 0; } captureFinish(); invalidateCache(); if (m_timerQuerySupport) { m_gpuTimer.destroy(); } if (m_occlusionQuerySupport) { m_occlusionQuery.destroy(); } destroyMsaaFbo(); m_glctx.destroy(); m_flip = false; unloadRenderDoc(m_renderdocdll); } RendererType::Enum getRendererType() const override { if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) ) { return RendererType::OpenGL; } return RendererType::OpenGLES; } const char* getRendererName() const override { return BGFX_RENDERER_OPENGL_NAME; } bool isDeviceRemoved() override { return false; } void flip() override { if (m_flip) { for (uint32_t ii = 1, num = m_numWindows; ii < num; ++ii) { FrameBufferGL& frameBuffer = m_frameBuffers[m_windows[ii].idx]; if (frameBuffer.m_needPresent) { m_glctx.swap(frameBuffer.m_swapChain); frameBuffer.m_needPresent = false; } } if (m_needPresent) { // Ensure the back buffer is bound as the source of the flip GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo)); m_glctx.swap(); m_needPresent = false; } } } void createIndexBuffer(IndexBufferHandle _handle, const Memory* _mem, uint16_t _flags) override { m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags); } void destroyIndexBuffer(IndexBufferHandle _handle) override { m_indexBuffers[_handle.idx].destroy(); } void createVertexLayout(VertexLayoutHandle _handle, const VertexLayout& _layout) override { VertexLayout& layout = m_vertexLayouts[_handle.idx]; bx::memCopy(&layout, &_layout, sizeof(VertexLayout) ); dump(layout); } void destroyVertexLayout(VertexLayoutHandle /*_handle*/) override { } void createVertexBuffer(VertexBufferHandle _handle, const Memory* _mem, VertexLayoutHandle _layoutHandle, uint16_t _flags) override { m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _layoutHandle, _flags); } void destroyVertexBuffer(VertexBufferHandle _handle) override { m_vertexBuffers[_handle.idx].destroy(); } void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) override { m_indexBuffers[_handle.idx].create(_size, NULL, _flags); } void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, const Memory* _mem) override { m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data); } void destroyDynamicIndexBuffer(IndexBufferHandle _handle) override { m_indexBuffers[_handle.idx].destroy(); } void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t _flags) override { VertexLayoutHandle layoutHandle = BGFX_INVALID_HANDLE; m_vertexBuffers[_handle.idx].create(_size, NULL, layoutHandle, _flags); } void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, const Memory* _mem) override { m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data); } void destroyDynamicVertexBuffer(VertexBufferHandle _handle) override { m_vertexBuffers[_handle.idx].destroy(); } void createShader(ShaderHandle _handle, const Memory* _mem) override { m_shaders[_handle.idx].create(_mem); } void destroyShader(ShaderHandle _handle) override { m_shaders[_handle.idx].destroy(); } void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) override { ShaderGL dummyFragmentShader; m_program[_handle.idx].create(m_shaders[_vsh.idx], isValid(_fsh) ? m_shaders[_fsh.idx] : dummyFragmentShader); } void destroyProgram(ProgramHandle _handle) override { m_program[_handle.idx].destroy(); } void* createTexture(TextureHandle _handle, const Memory* _mem, uint64_t _flags, uint8_t _skip) override { m_textures[_handle.idx].create(_mem, _flags, _skip); return NULL; } void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) override { } void updateTexture(TextureHandle _handle, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) override { m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem); } void updateTextureEnd() override { } void readTexture(TextureHandle _handle, void* _data, uint8_t _mip) override { if (m_readBackSupported) { const TextureGL& texture = m_textures[_handle.idx]; const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(texture.m_textureFormat) ); GL_CHECK(glBindTexture(texture.m_target, texture.m_id) ); if (compressed) { GL_CHECK(glGetCompressedTexImage(texture.m_target , _mip , _data ) ); } else { GL_CHECK(glGetTexImage(texture.m_target , _mip , texture.m_fmt , texture.m_type , _data ) ); } GL_CHECK(glBindTexture(texture.m_target, 0) ); } else { const TextureGL& texture = m_textures[_handle.idx]; const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(texture.m_textureFormat) ); if (!compressed) { Attachment at[1]; at[0].init(_handle); FrameBufferGL frameBuffer; frameBuffer.create(BX_COUNTOF(at), at); GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer.m_fbo[0]) ); GL_CHECK(glFramebufferTexture2D( GL_FRAMEBUFFER , GL_COLOR_ATTACHMENT0 , GL_TEXTURE_2D , texture.m_id , at[0].mip ) ); if (!BX_ENABLED(BX_PLATFORM_EMSCRIPTEN) && !BX_ENABLED(BX_PLATFORM_IOS) ) { GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0) ); } if (GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER) ) { GL_CHECK(glReadPixels( 0 , 0 , texture.m_width , texture.m_height , m_readPixelsFmt , GL_UNSIGNED_BYTE , _data ) ); } frameBuffer.destroy(); } } } void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips, uint16_t _numLayers) override { TextureGL& texture = m_textures[_handle.idx]; uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate); const Memory* mem = alloc(size); bx::StaticMemoryBlockWriter writer(mem->data, mem->size); uint32_t magic = BGFX_CHUNK_MAGIC_TEX; bx::write(&writer, magic); TextureCreate tc; tc.m_width = _width; tc.m_height = _height; tc.m_depth = 0; tc.m_numLayers = _numLayers; tc.m_numMips = _numMips; tc.m_format = TextureFormat::Enum(texture.m_requestedFormat); tc.m_cubeMap = false; tc.m_mem = NULL; bx::write(&writer, tc); texture.destroy(); texture.create(mem, texture.m_flags, 0); release(mem); } void overrideInternal(TextureHandle _handle, uintptr_t _ptr) override { m_textures[_handle.idx].overrideInternal(_ptr); } uintptr_t getInternal(TextureHandle _handle) override { return uintptr_t(m_textures[_handle.idx].m_id); } void destroyTexture(TextureHandle _handle) override { m_textures[_handle.idx].destroy(); } void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const Attachment* _attachment) override { m_frameBuffers[_handle.idx].create(_num, _attachment); } void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat) override { uint16_t denseIdx = m_numWindows++; m_windows[denseIdx] = _handle; m_frameBuffers[_handle.idx].create(denseIdx, _nwh, _width, _height, _format, _depthFormat); } void destroyFrameBuffer(FrameBufferHandle _handle) override { uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy(); if (UINT16_MAX != denseIdx) { --m_numWindows; if (m_numWindows > 1) { FrameBufferHandle handle = m_windows[m_numWindows]; m_windows[m_numWindows] = {kInvalidHandle}; if (m_numWindows != denseIdx) { m_windows[denseIdx] = handle; m_frameBuffers[handle.idx].m_denseIdx = denseIdx; } } } } void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) override { if (NULL != m_uniforms[_handle.idx]) { BX_FREE(g_allocator, m_uniforms[_handle.idx]); } uint32_t size = g_uniformTypeSize[_type]*_num; void* data = BX_ALLOC(g_allocator, size); bx::memSet(data, 0, size); m_uniforms[_handle.idx] = data; m_uniformReg.add(_handle, _name); } void destroyUniform(UniformHandle _handle) override { BX_FREE(g_allocator, m_uniforms[_handle.idx]); m_uniforms[_handle.idx] = NULL; m_uniformReg.remove(_handle); } void requestScreenShot(FrameBufferHandle _handle, const char* _filePath) override { SwapChainGL* swapChain = NULL; uint32_t width = m_resolution.width; uint32_t height = m_resolution.height; if (isValid(_handle) ) { const FrameBufferGL& frameBuffer = m_frameBuffers[_handle.idx]; swapChain = frameBuffer.m_swapChain; width = frameBuffer.m_width; height = frameBuffer.m_height; } m_glctx.makeCurrent(swapChain); uint32_t length = width*height*4; uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length); GL_CHECK(glReadPixels(0 , 0 , width , height , m_readPixelsFmt , GL_UNSIGNED_BYTE , data ) ); if (GL_RGBA == m_readPixelsFmt) { bimg::imageSwizzleBgra8(data, width*4, width, height, data, width*4); } g_callback->screenShot(_filePath , width , height , width*4 , data , length , true ); BX_FREE(g_allocator, data); } void updateViewName(ViewId _id, const char* _name) override { bx::strCopy(&s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED] , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED , _name ); } void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) override { bx::memCopy(m_uniforms[_loc], _data, _size); } void invalidateOcclusionQuery(OcclusionQueryHandle _handle) override { m_occlusionQuery.invalidate(_handle); } void setMarker(const char* _marker, uint16_t _len) override { GL_CHECK(glInsertEventMarker(_len, _marker) ); } virtual void setName(Handle _handle, const char* _name, uint16_t _len) override { uint16_t len = bx::min(_len, m_maxLabelLen); switch (_handle.type) { case Handle::IndexBuffer: GL_CHECK(glObjectLabel(GL_BUFFER, m_indexBuffers[_handle.idx].m_id, len, _name) ); break; case Handle::Shader: GL_CHECK(glObjectLabel(GL_SHADER, m_shaders[_handle.idx].m_id, len, _name) ); break; case Handle::Texture: { GLint id = m_textures[_handle.idx].m_id; if (0 != id) { GL_CHECK(glObjectLabel(GL_TEXTURE, id, len, _name) ); } else { GL_CHECK(glObjectLabel(GL_RENDERBUFFER, m_textures[_handle.idx].m_rbo, len, _name) ); } } break; case Handle::VertexBuffer: GL_CHECK(glObjectLabel(GL_BUFFER, m_vertexBuffers[_handle.idx].m_id, len, _name) ); break; default: BX_CHECK(false, "Invalid handle type?! %d", _handle.type); break; } } void submitBlit(BlitState& _bs, uint16_t _view); void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) override; void blitSetup(TextVideoMemBlitter& _blitter) override { if (0 != m_vao) { GL_CHECK(glBindVertexArray(m_vao) ); } uint32_t width = m_resolution.width; uint32_t height = m_resolution.height; GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) ); GL_CHECK(glViewport(0, 0, width, height) ); GL_CHECK(glDisable(GL_SCISSOR_TEST) ); GL_CHECK(glDisable(GL_STENCIL_TEST) ); GL_CHECK(glDisable(GL_DEPTH_TEST) ); GL_CHECK(glDepthFunc(GL_ALWAYS) ); GL_CHECK(glDisable(GL_CULL_FACE) ); GL_CHECK(glDisable(GL_BLEND) ); GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) ); ProgramGL& program = m_program[_blitter.m_program.idx]; GL_CHECK(glUseProgram(program.m_id) ); GL_CHECK(glUniform1i(program.m_sampler[0], 0) ); float proj[16]; bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f, 0.0f, g_caps.homogeneousDepth); GL_CHECK(glUniformMatrix4fv(program.m_predefined[0].m_loc , 1 , GL_FALSE , proj ) ); GL_CHECK(glActiveTexture(GL_TEXTURE0) ); GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_textures[_blitter.m_texture.idx].m_id) ); if (!BX_ENABLED(BX_PLATFORM_OSX) ) { if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) ) { if (m_samplerObjectSupport) { GL_CHECK(glBindSampler(0, 0) ); } } } } void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) override { const uint32_t numVertices = _numIndices*4/6; if (0 < numVertices) { m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices*2, _blitter.m_ib->data); m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_layout.m_stride, _blitter.m_vb->data); VertexBufferGL& vb = m_vertexBuffers[_blitter.m_vb->handle.idx]; GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) ); IndexBufferGL& ib = m_indexBuffers[_blitter.m_ib->handle.idx]; GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) ); ProgramGL& program = m_program[_blitter.m_program.idx]; program.bindAttributesBegin(); program.bindAttributes(_blitter.m_layout, 0); program.bindAttributesEnd(); GL_CHECK(glDrawElements(GL_TRIANGLES , _numIndices , GL_UNSIGNED_SHORT , (void*)0 ) ); } } void updateResolution(const Resolution& _resolution) { m_maxAnisotropy = !!(_resolution.reset & BGFX_RESET_MAXANISOTROPY) ? m_maxAnisotropyDefault : 0.0f ; if (s_extension[Extension::ARB_depth_clamp].m_supported) { if (!!(_resolution.reset & BGFX_RESET_DEPTH_CLAMP) ) { GL_CHECK(glEnable(GL_DEPTH_CLAMP) ); } else { GL_CHECK(glDisable(GL_DEPTH_CLAMP) ); } } const uint32_t maskFlags = ~(0 | BGFX_RESET_MAXANISOTROPY | BGFX_RESET_DEPTH_CLAMP | BGFX_RESET_SUSPEND ); if (m_resolution.width != _resolution.width || m_resolution.height != _resolution.height || (m_resolution.reset&maskFlags) != (_resolution.reset&maskFlags) ) { uint32_t flags = _resolution.reset & (~BGFX_RESET_INTERNAL_FORCE); m_resolution = _resolution; m_resolution.reset = flags; m_textVideoMem.resize(false, _resolution.width, _resolution.height); m_textVideoMem.clear(); setRenderContextSize(m_resolution.width , m_resolution.height , flags ); updateCapture(); for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii) { m_frameBuffers[ii].postReset(); } m_currentFbo = 0; GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_currentFbo) ); } } void setShaderUniform4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs) { GL_CHECK(glUniform4fv(_regIndex , _numRegs , (const GLfloat*)_val ) ); } void setShaderUniform4x4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs) { GL_CHECK(glUniformMatrix4fv(_regIndex , _numRegs , GL_FALSE , (const GLfloat*)_val ) ); } uint32_t setFrameBuffer(FrameBufferHandle _fbh, uint32_t _height, uint16_t _discard = BGFX_CLEAR_NONE, bool _msaa = true) { if (isValid(m_fbh) && m_fbh.idx != _fbh.idx) { FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx]; frameBuffer.resolve(); if (BGFX_CLEAR_NONE != m_fbDiscard) { frameBuffer.discard(m_fbDiscard); m_fbDiscard = BGFX_CLEAR_NONE; } } m_glctx.makeCurrent(NULL); if (!isValid(_fbh) ) { m_needPresent |= true; m_currentFbo = m_msaaBackBufferFbo; if (m_srgbWriteControlSupport) { if (0 != (m_resolution.reset & BGFX_RESET_SRGB_BACKBUFFER) ) { GL_CHECK(glEnable(GL_FRAMEBUFFER_SRGB) ); } else { GL_CHECK(glDisable(GL_FRAMEBUFFER_SRGB) ); } } } else { FrameBufferGL& frameBuffer = m_frameBuffers[_fbh.idx]; _height = frameBuffer.m_height; if (UINT16_MAX != frameBuffer.m_denseIdx) { m_glctx.makeCurrent(frameBuffer.m_swapChain); GL_CHECK(glFrontFace(GL_CW) ); frameBuffer.m_needPresent = true; m_currentFbo = 0; } else { m_glctx.makeCurrent(NULL); m_currentFbo = frameBuffer.m_fbo[0]; } frameBuffer.set(); } GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_currentFbo) ); m_fbh = _fbh; m_fbDiscard = _discard; m_rtMsaa = _msaa; return _height; } uint32_t getNumRt() const { if (isValid(m_fbh) ) { const FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx]; return frameBuffer.m_num; } return 1; } void createMsaaFbo(uint32_t _width, uint32_t _height, uint32_t _msaa) { if (0 == m_msaaBackBufferFbo // iOS && 1 < _msaa) { GLenum storageFormat = (m_resolution.reset & BGFX_RESET_SRGB_BACKBUFFER) ? GL_SRGB8_ALPHA8 : GL_RGBA8 ; GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) ); GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) ); GL_CHECK(glGenRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) ); GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) ); GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, storageFormat, _width, _height) ); GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) ); GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_DEPTH24_STENCIL8, _width, _height) ); GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) ); GLenum attachment = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT ; GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) ); BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER) , "glCheckFramebufferStatus failed 0x%08x" , glCheckFramebufferStatus(GL_FRAMEBUFFER) ); GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) ); } } void destroyMsaaFbo() { if (m_backBufferFbo != m_msaaBackBufferFbo // iOS && 0 != m_msaaBackBufferFbo) { GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) ); m_msaaBackBufferFbo = 0; if (0 != m_msaaBackBufferRbos[0]) { GL_CHECK(glDeleteRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) ); m_msaaBackBufferRbos[0] = 0; m_msaaBackBufferRbos[1] = 0; } } } void blitMsaaFbo() { if (m_backBufferFbo != m_msaaBackBufferFbo // iOS && 0 != m_msaaBackBufferFbo) { GL_CHECK(glDisable(GL_SCISSOR_TEST) ); GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) ); GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaBackBufferFbo) ); GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) ); uint32_t width = m_resolution.width; uint32_t height = m_resolution.height; GLenum filter = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) ? GL_NEAREST : GL_LINEAR ; GL_CHECK(glBlitFramebuffer(0 , 0 , width , height , 0 , 0 , width , height , GL_COLOR_BUFFER_BIT , filter ) ); GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) ); } } void setRenderContextSize(uint32_t _width, uint32_t _height, uint32_t _flags = 0) { if (_width != 0 || _height != 0) { if (!m_glctx.isValid() ) { m_glctx.create(_width, _height); #if BX_PLATFORM_IOS // iOS: need to figure out how to deal with FBO created by context. m_backBufferFbo = m_msaaBackBufferFbo = m_glctx.getFbo(); #endif // BX_PLATFORM_IOS } else { destroyMsaaFbo(); m_glctx.resize(_width, _height, _flags); uint32_t msaa = (_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT; msaa = bx::uint32_min(m_maxMsaa, msaa == 0 ? 0 : 1<<msaa); createMsaaFbo(_width, _height, msaa); } } m_flip = true; } void invalidateCache() { if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) ) && m_samplerObjectSupport) { m_samplerStateCache.invalidate(); } } void setSamplerState(uint32_t _stage, uint32_t _numMips, uint32_t _flags, const float _rgba[4]) { if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) ) && m_samplerObjectSupport) { if (0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & _flags) ) { const uint32_t index = (_flags & BGFX_SAMPLER_BORDER_COLOR_MASK) >> BGFX_SAMPLER_BORDER_COLOR_SHIFT; _flags &= ~BGFX_SAMPLER_RESERVED_MASK; _flags &= BGFX_SAMPLER_BITS_MASK; _flags |= _numMips<<BGFX_SAMPLER_RESERVED_SHIFT; GLuint sampler; bool hasBorderColor = false; bx::HashMurmur2A murmur; uint32_t hash; murmur.begin(); murmur.add(_flags); if (!needBorderColor(_flags) ) { murmur.add(-1); hash = murmur.end(); sampler = m_samplerStateCache.find(hash); } else { murmur.add(index); hash = murmur.end(); if (NULL != _rgba) { hasBorderColor = true; sampler = UINT32_MAX; } else { sampler = m_samplerStateCache.find(hash); } } if (UINT32_MAX == sampler) { sampler = m_samplerStateCache.add(hash); GL_CHECK(glSamplerParameteri(sampler , GL_TEXTURE_WRAP_S , s_textureAddress[(_flags&BGFX_SAMPLER_U_MASK)>>BGFX_SAMPLER_U_SHIFT] ) ); GL_CHECK(glSamplerParameteri(sampler , GL_TEXTURE_WRAP_T , s_textureAddress[(_flags&BGFX_SAMPLER_V_MASK)>>BGFX_SAMPLER_V_SHIFT] ) ); GL_CHECK(glSamplerParameteri(sampler , GL_TEXTURE_WRAP_R , s_textureAddress[(_flags&BGFX_SAMPLER_W_MASK)>>BGFX_SAMPLER_W_SHIFT] ) ); GLenum minFilter; GLenum magFilter; getFilters(_flags, 1 < _numMips, magFilter, minFilter); GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, magFilter) ); GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, minFilter) ); if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) ) { GL_CHECK(glSamplerParameterf(sampler, GL_TEXTURE_LOD_BIAS, float(BGFX_CONFIG_MIP_LOD_BIAS) ) ); } if (m_borderColorSupport && hasBorderColor) { GL_CHECK(glSamplerParameterfv(sampler, GL_TEXTURE_BORDER_COLOR, _rgba) ); } if (0 != (_flags & (BGFX_SAMPLER_MIN_ANISOTROPIC|BGFX_SAMPLER_MAG_ANISOTROPIC) ) && 0.0f < m_maxAnisotropy) { GL_CHECK(glSamplerParameterf(sampler, GL_TEXTURE_MAX_ANISOTROPY_EXT, m_maxAnisotropy) ); } if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) || m_shadowSamplersSupport) { const uint32_t cmpFunc = (_flags&BGFX_SAMPLER_COMPARE_MASK)>>BGFX_SAMPLER_COMPARE_SHIFT; if (0 == cmpFunc) { GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_NONE) ); } else { GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) ); GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) ); } } } GL_CHECK(glBindSampler(_stage, sampler) ); } else { GL_CHECK(glBindSampler(_stage, 0) ); } } } bool isVisible(Frame* _render, OcclusionQueryHandle _handle, bool _visible) { m_occlusionQuery.resolve(_render); return _visible == (0 != _render->m_occlusion[_handle.idx]); } void updateCapture() { if (m_resolution.reset&BGFX_RESET_CAPTURE) { m_captureSize = m_resolution.width*m_resolution.height*4; m_capture = BX_REALLOC(g_allocator, m_capture, m_captureSize); g_callback->captureBegin(m_resolution.width, m_resolution.height, m_resolution.width*4, TextureFormat::BGRA8, true); } else { captureFinish(); } } void capture() { if (NULL != m_capture) { GL_CHECK(glReadPixels(0 , 0 , m_resolution.width , m_resolution.height , m_readPixelsFmt , GL_UNSIGNED_BYTE , m_capture ) ); if (GL_RGBA == m_readPixelsFmt) { bimg::imageSwizzleBgra8( m_capture , m_resolution.width*4 , m_resolution.width , m_resolution.height , m_capture , m_resolution.width*4 ); } g_callback->captureFrame(m_capture, m_captureSize); } } void captureFinish() { if (NULL != m_capture) { g_callback->captureEnd(); BX_FREE(g_allocator, m_capture); m_capture = NULL; m_captureSize = 0; } } bool programFetchFromCache(GLuint programId, uint64_t _id) { _id ^= m_hash; bool cached = false; if (m_programBinarySupport) { uint32_t length = g_callback->cacheReadSize(_id); cached = length > 0; if (cached) { void* data = BX_ALLOC(g_allocator, length); if (g_callback->cacheRead(_id, data, length) ) { bx::MemoryReader reader(data, length); GLenum format; bx::read(&reader, format); GL_CHECK(glProgramBinary(programId, format, reader.getDataPtr(), (GLsizei)reader.remaining() ) ); } BX_FREE(g_allocator, data); } #if BGFX_CONFIG_RENDERER_OPENGL GL_CHECK(glProgramParameteri(programId, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) ); #endif // BGFX_CONFIG_RENDERER_OPENGL } return cached; } void programCache(GLuint programId, uint64_t _id) { _id ^= m_hash; if (m_programBinarySupport) { GLint programLength; GLenum format; GL_CHECK(glGetProgramiv(programId, GL_PROGRAM_BINARY_LENGTH, &programLength) ); if (0 < programLength) { uint32_t length = programLength + 4; uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length); GL_CHECK(glGetProgramBinary(programId, programLength, NULL, &format, &data[4]) ); *(uint32_t*)data = format; g_callback->cacheWrite(_id, data, length); BX_FREE(g_allocator, data); } } } void commit(UniformBuffer& _uniformBuffer) { _uniformBuffer.reset(); for (;;) { uint32_t opcode = _uniformBuffer.read(); if (UniformType::End == opcode) { break; } UniformType::Enum type; uint16_t ignore; uint16_t num; uint16_t copy; UniformBuffer::decodeOpcode(opcode, type, ignore, num, copy); const char* data; if (copy) { data = _uniformBuffer.read(g_uniformTypeSize[type]*num); } else { UniformHandle handle; bx::memCopy(&handle, _uniformBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) ); data = (const char*)m_uniforms[handle.idx]; } uint32_t loc = _uniformBuffer.read(); #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \ case UniformType::_uniform: \ { \ _type* value = (_type*)data; \ GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \ } \ break; #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \ case UniformType::_uniform: \ { \ _type* value = (_type*)data; \ GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \ } \ break; switch (type) { CASE_IMPLEMENT_UNIFORM(Sampler, 1iv, I, int); CASE_IMPLEMENT_UNIFORM(Vec4, 4fv, F, float); CASE_IMPLEMENT_UNIFORM_T(Mat3, Matrix3fv, F, float); CASE_IMPLEMENT_UNIFORM_T(Mat4, Matrix4fv, F, float); case UniformType::End: break; default: BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _uniformBuffer.getPos(), opcode, type, loc, num, copy); break; } #undef CASE_IMPLEMENT_UNIFORM #undef CASE_IMPLEMENT_UNIFORM_T } } void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, uint32_t _height, const float _palette[][4]) { uint32_t numMrt = 1; FrameBufferHandle fbh = m_fbh; if (isValid(fbh) ) { const FrameBufferGL& fb = m_frameBuffers[fbh.idx]; numMrt = bx::uint32_max(1, fb.m_num); } if (1 == numMrt) { GLuint flags = 0; if (BGFX_CLEAR_COLOR & _clear.m_flags) { if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags) { uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[0]); const float* rgba = _palette[index]; const float rr = rgba[0]; const float gg = rgba[1]; const float bb = rgba[2]; const float aa = rgba[3]; GL_CHECK(glClearColor(rr, gg, bb, aa) ); } else { float rr = _clear.m_index[0]*1.0f/255.0f; float gg = _clear.m_index[1]*1.0f/255.0f; float bb = _clear.m_index[2]*1.0f/255.0f; float aa = _clear.m_index[3]*1.0f/255.0f; GL_CHECK(glClearColor(rr, gg, bb, aa) ); } flags |= GL_COLOR_BUFFER_BIT; GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) ); } if (BGFX_CLEAR_DEPTH & _clear.m_flags) { flags |= GL_DEPTH_BUFFER_BIT; GL_CHECK(glClearDepth(_clear.m_depth) ); GL_CHECK(glDepthMask(GL_TRUE) ); } if (BGFX_CLEAR_STENCIL & _clear.m_flags) { flags |= GL_STENCIL_BUFFER_BIT; GL_CHECK(glClearStencil(_clear.m_stencil) ); } if (0 != flags) { GL_CHECK(glEnable(GL_SCISSOR_TEST) ); GL_CHECK(glScissor(_rect.m_x, _height-_rect.m_height-_rect.m_y, _rect.m_width, _rect.m_height) ); GL_CHECK(glClear(flags) ); GL_CHECK(glDisable(GL_SCISSOR_TEST) ); } } else { const GLuint defaultVao = m_vao; if (0 != defaultVao) { GL_CHECK(glBindVertexArray(defaultVao) ); } GL_CHECK(glDisable(GL_SCISSOR_TEST) ); GL_CHECK(glDisable(GL_CULL_FACE) ); GL_CHECK(glDisable(GL_BLEND) ); GLboolean colorMask = !!(BGFX_CLEAR_COLOR & _clear.m_flags); GL_CHECK(glColorMask(colorMask, colorMask, colorMask, colorMask) ); if (BGFX_CLEAR_DEPTH & _clear.m_flags) { GL_CHECK(glEnable(GL_DEPTH_TEST) ); GL_CHECK(glDepthFunc(GL_ALWAYS) ); GL_CHECK(glDepthMask(GL_TRUE) ); } else { GL_CHECK(glDisable(GL_DEPTH_TEST) ); } if (BGFX_CLEAR_STENCIL & _clear.m_flags) { GL_CHECK(glEnable(GL_STENCIL_TEST) ); GL_CHECK(glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, _clear.m_stencil, 0xff) ); GL_CHECK(glStencilOpSeparate(GL_FRONT_AND_BACK, GL_REPLACE, GL_REPLACE, GL_REPLACE) ); } else { GL_CHECK(glDisable(GL_STENCIL_TEST) ); } VertexBufferGL& vb = m_vertexBuffers[_clearQuad.m_vb.idx]; VertexLayout& layout = _clearQuad.m_layout; GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) ); ProgramGL& program = m_program[_clearQuad.m_program[numMrt-1].idx]; GL_CHECK(glUseProgram(program.m_id) ); program.bindAttributesBegin(); program.bindAttributes(layout, 0); program.bindAttributesEnd(); if (m_clearQuadColor.idx == kInvalidHandle) { const UniformRegInfo* infoClearColor = m_uniformReg.find("bgfx_clear_color"); if (NULL != infoClearColor) m_clearQuadColor = infoClearColor->m_handle; } if (m_clearQuadDepth.idx == kInvalidHandle) { const UniformRegInfo* infoClearDepth = m_uniformReg.find("bgfx_clear_depth"); if (NULL != infoClearDepth) m_clearQuadDepth = infoClearDepth->m_handle; } float mrtClearDepth[4] = { g_caps.homogeneousDepth ? (_clear.m_depth * 2.0f - 1.0f) : _clear.m_depth }; updateUniform(m_clearQuadDepth.idx, mrtClearDepth, sizeof(float)*4); float mrtClearColor[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4]; if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags) { for (uint32_t ii = 0; ii < numMrt; ++ii) { uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[ii]); bx::memCopy(mrtClearColor[ii], _palette[index], 16); } } else { float rgba[4] = { _clear.m_index[0] * 1.0f / 255.0f, _clear.m_index[1] * 1.0f / 255.0f, _clear.m_index[2] * 1.0f / 255.0f, _clear.m_index[3] * 1.0f / 255.0f, }; for (uint32_t ii = 0; ii < numMrt; ++ii) { bx::memCopy(mrtClearColor[ii], rgba, 16); } } updateUniform(m_clearQuadColor.idx, mrtClearColor[0], numMrt * sizeof(float) * 4); commit(*program.m_constantBuffer); GL_CHECK(glDrawArrays(GL_TRIANGLE_STRIP , 0 , 4 ) ); } } void* m_renderdocdll; uint16_t m_numWindows; FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS]; IndexBufferGL m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS]; VertexBufferGL m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS]; ShaderGL m_shaders[BGFX_CONFIG_MAX_SHADERS]; ProgramGL m_program[BGFX_CONFIG_MAX_PROGRAMS]; TextureGL m_textures[BGFX_CONFIG_MAX_TEXTURES]; VertexLayout m_vertexLayouts[BGFX_CONFIG_MAX_VERTEX_LAYOUTS]; FrameBufferGL m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS]; UniformRegistry m_uniformReg; void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS]; TimerQueryGL m_gpuTimer; OcclusionQueryGL m_occlusionQuery; SamplerStateCache m_samplerStateCache; TextVideoMem m_textVideoMem; bool m_rtMsaa; FrameBufferHandle m_fbh; uint16_t m_fbDiscard; Resolution m_resolution; void* m_capture; uint32_t m_captureSize; float m_maxAnisotropy; float m_maxAnisotropyDefault; int32_t m_maxMsaa; GLuint m_vao; uint16_t m_maxLabelLen; bool m_blitSupported; bool m_readBackSupported; bool m_vaoSupport; bool m_samplerObjectSupport; bool m_shadowSamplersSupport; bool m_srgbWriteControlSupport; bool m_borderColorSupport; bool m_programBinarySupport; bool m_textureSwizzleSupport; bool m_depthTextureSupport; bool m_timerQuerySupport; bool m_occlusionQuerySupport; bool m_atocSupport; bool m_conservativeRasterSupport; bool m_imageLoadStoreSupport; bool m_flip; uint64_t m_hash; GLenum m_readPixelsFmt; GLuint m_backBufferFbo; GLuint m_msaaBackBufferFbo; GLuint m_msaaBackBufferRbos[2]; GlContext m_glctx; bool m_needPresent; UniformHandle m_clearQuadColor; UniformHandle m_clearQuadDepth; const char* m_vendor; const char* m_renderer; const char* m_version; const char* m_glslVersion; Workaround m_workaround; GLuint m_currentFbo; }; RendererContextGL* s_renderGL; RendererContextI* rendererCreate(const Init& _init) { s_renderGL = BX_NEW(g_allocator, RendererContextGL); if (!s_renderGL->init(_init) ) { BX_DELETE(g_allocator, s_renderGL); s_renderGL = NULL; } return s_renderGL; } void rendererDestroy() { s_renderGL->shutdown(); BX_DELETE(g_allocator, s_renderGL); s_renderGL = NULL; } static void frameBufferValidate() { GLenum complete = glCheckFramebufferStatus(GL_FRAMEBUFFER); BX_CHECK(GL_FRAMEBUFFER_COMPLETE == complete , "glCheckFramebufferStatus failed 0x%08x: %s" , complete , glEnumName(complete) ); BX_UNUSED(complete); } const char* glslTypeName(GLuint _type) { #define GLSL_TYPE(_ty) case _ty: return #_ty switch (_type) { GLSL_TYPE(GL_BOOL); GLSL_TYPE(GL_INT); GLSL_TYPE(GL_INT_VEC2); GLSL_TYPE(GL_INT_VEC3); GLSL_TYPE(GL_INT_VEC4); GLSL_TYPE(GL_UNSIGNED_INT); GLSL_TYPE(GL_UNSIGNED_INT_VEC2); GLSL_TYPE(GL_UNSIGNED_INT_VEC3); GLSL_TYPE(GL_UNSIGNED_INT_VEC4); GLSL_TYPE(GL_FLOAT); GLSL_TYPE(GL_FLOAT_VEC2); GLSL_TYPE(GL_FLOAT_VEC3); GLSL_TYPE(GL_FLOAT_VEC4); GLSL_TYPE(GL_FLOAT_MAT2); GLSL_TYPE(GL_FLOAT_MAT3); GLSL_TYPE(GL_FLOAT_MAT4); GLSL_TYPE(GL_SAMPLER_2D); GLSL_TYPE(GL_SAMPLER_2D_ARRAY); GLSL_TYPE(GL_SAMPLER_2D_MULTISAMPLE); GLSL_TYPE(GL_INT_SAMPLER_2D); GLSL_TYPE(GL_INT_SAMPLER_2D_ARRAY); GLSL_TYPE(GL_INT_SAMPLER_2D_MULTISAMPLE); GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D); GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY); GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE); GLSL_TYPE(GL_SAMPLER_2D_SHADOW); GLSL_TYPE(GL_SAMPLER_2D_ARRAY_SHADOW); GLSL_TYPE(GL_SAMPLER_3D); GLSL_TYPE(GL_INT_SAMPLER_3D); GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_3D); GLSL_TYPE(GL_SAMPLER_CUBE); GLSL_TYPE(GL_INT_SAMPLER_CUBE); GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_CUBE); GLSL_TYPE(GL_IMAGE_1D); GLSL_TYPE(GL_INT_IMAGE_1D); GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_1D); GLSL_TYPE(GL_IMAGE_2D); GLSL_TYPE(GL_IMAGE_2D_ARRAY); GLSL_TYPE(GL_INT_IMAGE_2D); GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_2D); GLSL_TYPE(GL_IMAGE_3D); GLSL_TYPE(GL_INT_IMAGE_3D); GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_3D); GLSL_TYPE(GL_IMAGE_CUBE); GLSL_TYPE(GL_INT_IMAGE_CUBE); GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_CUBE); } #undef GLSL_TYPE BX_CHECK(false, "Unknown GLSL type? %x", _type); return "UNKNOWN GLSL TYPE!"; } const char* glEnumName(GLenum _enum) { #define GLENUM(_ty) case _ty: return #_ty switch (_enum) { GLENUM(GL_TEXTURE); GLENUM(GL_RENDERBUFFER); GLENUM(GL_INVALID_ENUM); GLENUM(GL_INVALID_FRAMEBUFFER_OPERATION); GLENUM(GL_INVALID_VALUE); GLENUM(GL_INVALID_OPERATION); GLENUM(GL_OUT_OF_MEMORY); GLENUM(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT); GLENUM(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT); // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER); // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER); GLENUM(GL_FRAMEBUFFER_UNSUPPORTED); } #undef GLENUM BX_WARN(false, "Unknown enum? %x", _enum); return "<GLenum?>"; } UniformType::Enum convertGlType(GLenum _type) { switch (_type) { case GL_INT: case GL_UNSIGNED_INT: return UniformType::Sampler; case GL_FLOAT: case GL_FLOAT_VEC2: case GL_FLOAT_VEC3: case GL_FLOAT_VEC4: return UniformType::Vec4; case GL_FLOAT_MAT2: break; case GL_FLOAT_MAT3: return UniformType::Mat3; case GL_FLOAT_MAT4: return UniformType::Mat4; case GL_SAMPLER_2D: case GL_SAMPLER_2D_ARRAY: case GL_SAMPLER_2D_MULTISAMPLE: case GL_INT_SAMPLER_2D: case GL_INT_SAMPLER_2D_ARRAY: case GL_INT_SAMPLER_2D_MULTISAMPLE: case GL_UNSIGNED_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: case GL_SAMPLER_2D_SHADOW: case GL_SAMPLER_2D_ARRAY_SHADOW: case GL_SAMPLER_3D: case GL_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_3D: case GL_SAMPLER_CUBE: case GL_INT_SAMPLER_CUBE: case GL_UNSIGNED_INT_SAMPLER_CUBE: case GL_IMAGE_1D: case GL_INT_IMAGE_1D: case GL_UNSIGNED_INT_IMAGE_1D: case GL_IMAGE_2D: case GL_IMAGE_2D_ARRAY: case GL_INT_IMAGE_2D: case GL_UNSIGNED_INT_IMAGE_2D: case GL_IMAGE_3D: case GL_INT_IMAGE_3D: case GL_UNSIGNED_INT_IMAGE_3D: case GL_IMAGE_CUBE: case GL_INT_IMAGE_CUBE: case GL_UNSIGNED_INT_IMAGE_CUBE: return UniformType::Sampler; }; BX_CHECK(false, "Unrecognized GL type 0x%04x.", _type); return UniformType::End; } void ProgramGL::create(const ShaderGL& _vsh, const ShaderGL& _fsh) { m_id = glCreateProgram(); BX_TRACE("Program create: GL%d: GL%d, GL%d", m_id, _vsh.m_id, _fsh.m_id); const uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash; const bool cached = s_renderGL->programFetchFromCache(m_id, id); if (!cached) { GLint linked = 0; if (0 != _vsh.m_id) { GL_CHECK(glAttachShader(m_id, _vsh.m_id) ); if (0 != _fsh.m_id) { GL_CHECK(glAttachShader(m_id, _fsh.m_id) ); } GL_CHECK(glLinkProgram(m_id) ); GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) ); if (0 == linked) { char log[1024]; GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) ); BX_TRACE("%d: %s", linked, log); } } if (0 == linked) { BX_WARN(0 != _vsh.m_id, "Invalid vertex/compute shader."); GL_CHECK(glDeleteProgram(m_id) ); m_usedCount = 0; m_id = 0; return; } s_renderGL->programCache(m_id, id); } init(); if (!cached && s_renderGL->m_workaround.m_detachShader) { // Must be after init, otherwise init might fail to lookup shader // info (NVIDIA Tegra 3 OpenGL ES 2.0 14.01003). GL_CHECK(glDetachShader(m_id, _vsh.m_id) ); if (0 != _fsh.m_id) { GL_CHECK(glDetachShader(m_id, _fsh.m_id) ); } } } void ProgramGL::destroy() { if (NULL != m_constantBuffer) { UniformBuffer::destroy(m_constantBuffer); m_constantBuffer = NULL; } m_numPredefined = 0; if (0 != m_id) { GL_CHECK(glUseProgram(0) ); GL_CHECK(glDeleteProgram(m_id) ); m_id = 0; } } void ProgramGL::init() { GLint activeAttribs = 0; GLint activeUniforms = 0; GLint activeBuffers = 0; #if BGFX_CONFIG_RENDERER_OPENGL >= 31 GL_CHECK(glBindFragDataLocation(m_id, 0, "bgfx_FragColor") ); #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31 GLint max0, max1; bool piqSupported = true && s_extension[Extension::ARB_program_interface_query ].m_supported && s_extension[Extension::ARB_shader_storage_buffer_object].m_supported ; if (piqSupported) { GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &activeAttribs ) ); GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_ACTIVE_RESOURCES, &activeUniforms) ); GL_CHECK(glGetProgramInterfaceiv(m_id, GL_BUFFER_VARIABLE, GL_ACTIVE_RESOURCES, &activeBuffers ) ); GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_MAX_NAME_LENGTH, &max0 ) ); GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_MAX_NAME_LENGTH, &max1 ) ); } else { GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs ) ); GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) ); GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) ); GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) ); } uint32_t maxLength = bx::uint32_max(max0, max1); char* name = (char*)alloca(maxLength + 1); BX_TRACE("Program %d", m_id); BX_TRACE("Attributes (%d):", activeAttribs); for (int32_t ii = 0; ii < activeAttribs; ++ii) { GLint size; GLenum type = 0; if (piqSupported) { GL_CHECK(glGetProgramResourceName(m_id, GL_PROGRAM_INPUT, ii, maxLength + 1, &size, name) ); GLenum typeProp[] = { GL_TYPE }; GL_CHECK(glGetProgramResourceiv(m_id , GL_PROGRAM_INPUT , ii , BX_COUNTOF(typeProp) , typeProp , 1 , NULL , (GLint *)&type) ); } else { GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) ); } BX_TRACE("\t%s %s is at location %d" , glslTypeName(type) , name , glGetAttribLocation(m_id, name) ); } m_numPredefined = 0; m_numSamplers = 0; BX_TRACE("Uniforms (%d):", activeUniforms); for (int32_t ii = 0; ii < activeUniforms; ++ii) { struct VariableInfo { GLenum type; GLint loc; GLint num; }; VariableInfo vi; GLenum props[] = { GL_TYPE, GL_LOCATION, GL_ARRAY_SIZE }; GLenum gltype; GLint num; GLint loc; if (piqSupported) { GL_CHECK(glGetProgramResourceiv(m_id , GL_UNIFORM , ii , BX_COUNTOF(props) , props , BX_COUNTOF(props) , NULL , (GLint*)&vi ) ); GL_CHECK(glGetProgramResourceName(m_id , GL_UNIFORM , ii , maxLength + 1 , NULL , name ) ); gltype = vi.type; loc = vi.loc; num = vi.num; } else { GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) ); loc = glGetUniformLocation(m_id, name); } num = bx::uint32_max(num, 1); int32_t offset = 0; const bx::StringView array = bx::strFind(name, '['); if (!array.isEmpty() ) { name[array.getPtr() - name] = '\0'; BX_TRACE("--- %s", name); const bx::StringView end = bx::strFind(array.getPtr()+1, ']'); bx::fromString(&offset, bx::StringView(array.getPtr()+1, end.getPtr() ) ); } switch (gltype) { case GL_SAMPLER_2D: case GL_SAMPLER_2D_ARRAY: case GL_SAMPLER_2D_MULTISAMPLE: case GL_INT_SAMPLER_2D: case GL_INT_SAMPLER_2D_ARRAY: case GL_INT_SAMPLER_2D_MULTISAMPLE: case GL_UNSIGNED_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: case GL_SAMPLER_2D_SHADOW: case GL_SAMPLER_2D_ARRAY_SHADOW: case GL_SAMPLER_3D: case GL_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_3D: case GL_SAMPLER_CUBE: case GL_INT_SAMPLER_CUBE: case GL_UNSIGNED_INT_SAMPLER_CUBE: case GL_IMAGE_1D: case GL_INT_IMAGE_1D: case GL_UNSIGNED_INT_IMAGE_1D: case GL_IMAGE_2D: case GL_INT_IMAGE_2D: case GL_UNSIGNED_INT_IMAGE_2D: case GL_IMAGE_3D: case GL_INT_IMAGE_3D: case GL_UNSIGNED_INT_IMAGE_3D: case GL_IMAGE_CUBE: case GL_INT_IMAGE_CUBE: case GL_UNSIGNED_INT_IMAGE_CUBE: if (m_numSamplers < BX_COUNTOF(m_sampler) ) { BX_TRACE("Sampler #%d at location %d.", m_numSamplers, loc); m_sampler[m_numSamplers] = loc; m_numSamplers++; } else { BX_TRACE("Too many samplers (max: %d)! Sampler at location %d." , BX_COUNTOF(m_sampler) , loc ); } break; default: break; } PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name); if (PredefinedUniform::Count != predefined) { m_predefined[m_numPredefined].m_loc = loc; m_predefined[m_numPredefined].m_count = uint16_t(num); m_predefined[m_numPredefined].m_type = uint8_t(predefined); m_numPredefined++; } else { const UniformRegInfo* info = s_renderGL->m_uniformReg.find(name); BX_WARN(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name); if (NULL != info) { if (NULL == m_constantBuffer) { m_constantBuffer = UniformBuffer::create(1024); } UniformType::Enum type = convertGlType(gltype); m_constantBuffer->writeUniformHandle(type, 0, info->m_handle, uint16_t(num) ); m_constantBuffer->write(loc); BX_TRACE("store %s %d", name, info->m_handle); } } BX_TRACE("\tuniform %s %s%s is at location %d, size %d, offset %d" , glslTypeName(gltype) , name , PredefinedUniform::Count != predefined ? "*" : "" , loc , num , offset ); BX_UNUSED(offset); } if (NULL != m_constantBuffer) { m_constantBuffer->finish(); } if (piqSupported) { struct VariableInfo { GLenum type; }; VariableInfo vi; GLenum props[] = { GL_TYPE }; BX_TRACE("Buffers (%d):", activeBuffers); for (int32_t ii = 0; ii < activeBuffers; ++ii) { GL_CHECK(glGetProgramResourceiv(m_id , GL_BUFFER_VARIABLE , ii , BX_COUNTOF(props) , props , BX_COUNTOF(props) , NULL , (GLint*)&vi ) ); GL_CHECK(glGetProgramResourceName(m_id , GL_BUFFER_VARIABLE , ii , maxLength + 1 , NULL , name ) ); BX_TRACE("\t%s %s at %d" , glslTypeName(vi.type) , name , 0 //vi.loc ); } } bx::memSet(m_attributes, 0xff, sizeof(m_attributes) ); uint32_t used = 0; for (uint8_t ii = 0; ii < Attrib::Count; ++ii) { GLint loc = glGetAttribLocation(m_id, s_attribName[ii]); if (-1 != loc) { BX_TRACE("attr %s: %d", s_attribName[ii], loc); m_attributes[ii] = loc; m_used[used++] = ii; } } BX_CHECK(used < BX_COUNTOF(m_used), "Out of bounds %d > array size %d.", used, Attrib::Count); m_usedCount = (uint8_t)used; used = 0; for (uint32_t ii = 0; ii < BX_COUNTOF(s_instanceDataName); ++ii) { GLuint loc = glGetAttribLocation(m_id, s_instanceDataName[ii]); if (GLuint(-1) != loc ) { BX_TRACE("instance data %s: %d", s_instanceDataName[ii], loc); m_instanceData[used++] = loc; } } BX_CHECK(used < BX_COUNTOF(m_instanceData), "Out of bounds %d > array size %d." , used , BX_COUNTOF(m_instanceData) ); m_instanceData[used] = 0xffff; } void ProgramGL::bindAttributes(const VertexLayout& _layout, uint32_t _baseVertex) { for (uint32_t ii = 0, iiEnd = m_usedCount; ii < iiEnd; ++ii) { Attrib::Enum attr = Attrib::Enum(m_used[ii]); GLint loc = m_attributes[attr]; uint8_t num; AttribType::Enum type; bool normalized; bool asInt; _layout.decode(attr, num, type, normalized, asInt); if (-1 != loc) { if (UINT16_MAX != _layout.m_attributes[attr]) { GL_CHECK(glEnableVertexAttribArray(loc) ); GL_CHECK(glVertexAttribDivisor(loc, 0) ); uint32_t baseVertex = _baseVertex*_layout.m_stride + _layout.m_offset[attr]; if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 30) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) ) && (AttribType::Uint8 == type || AttribType::Int16 == type) && !normalized) { GL_CHECK(glVertexAttribIPointer(loc , num , s_attribType[type] , _layout.m_stride , (void*)(uintptr_t)baseVertex) ); } else { GL_CHECK(glVertexAttribPointer(loc , num , s_attribType[type] , normalized , _layout.m_stride , (void*)(uintptr_t)baseVertex) ); } m_unboundUsedAttrib[ii] = Attrib::Count; } } } } void ProgramGL::unbindAttributes() { for(uint32_t ii = 0, iiEnd = m_usedCount; ii < iiEnd; ++ii) { if(Attrib::Count == m_unboundUsedAttrib[ii]) { Attrib::Enum attr = Attrib::Enum(m_used[ii]); GLint loc = m_attributes[attr]; GL_CHECK(glDisableVertexAttribArray(loc)); } } } void ProgramGL::bindInstanceData(uint32_t _stride, uint32_t _baseVertex) const { uint32_t baseVertex = _baseVertex; for (uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii) { GLint loc = m_instanceData[ii]; GL_CHECK(glEnableVertexAttribArray(loc) ); GL_CHECK(glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, _stride, (void*)(uintptr_t)baseVertex) ); GL_CHECK(glVertexAttribDivisor(loc, 1) ); baseVertex += 16; } } void ProgramGL::unbindInstanceData() const { for(uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii) { GLint loc = m_instanceData[ii]; GL_CHECK(glDisableVertexAttribArray(loc)); } } void IndexBufferGL::destroy() { GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) ); GL_CHECK(glDeleteBuffers(1, &m_id) ); } void VertexBufferGL::destroy() { GL_CHECK(glBindBuffer(m_target, 0) ); GL_CHECK(glDeleteBuffers(1, &m_id) ); } bool TextureGL::init(GLenum _target, uint32_t _width, uint32_t _height, uint32_t _depth, uint8_t _numMips, uint64_t _flags) { m_target = _target; m_numMips = _numMips; m_flags = _flags; m_width = _width; m_height = _height; m_depth = _depth; m_currentSamplerHash = UINT32_MAX; const bool writeOnly = 0 != (m_flags&BGFX_TEXTURE_RT_WRITE_ONLY); const bool computeWrite = 0 != (m_flags&BGFX_TEXTURE_COMPUTE_WRITE ); const bool srgb = 0 != (m_flags&BGFX_TEXTURE_SRGB); const bool textureArray = false || _target == GL_TEXTURE_2D_ARRAY || _target == GL_TEXTURE_CUBE_MAP_ARRAY ; if (!writeOnly) { GL_CHECK(glGenTextures(1, &m_id) ); BX_CHECK(0 != m_id, "Failed to generate texture id."); GL_CHECK(glBindTexture(_target, m_id) ); GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) ); const TextureFormatInfo& tfi = s_textureFormat[m_textureFormat]; m_fmt = tfi.m_fmt; m_type = tfi.m_type; const bool swizzle = true && TextureFormat::BGRA8 == m_requestedFormat && !s_textureFormat[m_requestedFormat].m_supported && !s_renderGL->m_textureSwizzleSupport ; const bool convert = false || m_textureFormat != m_requestedFormat || swizzle ; if (convert) { m_textureFormat = (uint8_t)TextureFormat::RGBA8; const TextureFormatInfo& tfiRgba8 = s_textureFormat[TextureFormat::RGBA8]; m_fmt = tfiRgba8.m_fmt; m_type = tfiRgba8.m_type; } const GLenum internalFmt = srgb ? s_textureFormat[m_textureFormat].m_internalFmtSrgb : s_textureFormat[m_textureFormat].m_internalFmt ; if (textureArray) { GL_CHECK(glTexStorage3D(_target , _numMips , internalFmt , m_width , m_height , _depth ) ); } else if (computeWrite) { if (_target == GL_TEXTURE_3D) { GL_CHECK(glTexStorage3D(_target , _numMips , internalFmt , m_width , m_height , _depth ) ); } else { GL_CHECK(glTexStorage2D(_target , _numMips , internalFmt , m_width , m_height ) ); } } setSamplerState(uint32_t(_flags), NULL); if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && TextureFormat::BGRA8 == m_requestedFormat && !s_textureFormat[m_requestedFormat].m_supported && s_renderGL->m_textureSwizzleSupport) { GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA }; GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) ); } } const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK); if (renderTarget) { uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT); msaaQuality = bx::uint32_satsub(msaaQuality, 1); msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality); const bool msaaSample = 0 != (m_flags&BGFX_TEXTURE_MSAA_SAMPLE); if (!msaaSample && (0 != msaaQuality || writeOnly) ) { GL_CHECK(glGenRenderbuffers(1, &m_rbo) ); BX_CHECK(0 != m_rbo, "Failed to generate renderbuffer id."); GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_rbo) ); if (0 == msaaQuality) { GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER , s_rboFormat[m_textureFormat] , _width , _height ) ); } else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) ) { GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER , msaaQuality , s_rboFormat[m_textureFormat] , _width , _height ) ); } GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) ); if (writeOnly) { // This is render buffer, there is no sampling, no need // to create texture. return false; } } } return true; } void TextureGL::create(const Memory* _mem, uint64_t _flags, uint8_t _skip) { bimg::ImageContainer imageContainer; if (bimg::imageParse(imageContainer, _mem->data, _mem->size) ) { const uint8_t startLod = bx::min<uint8_t>(_skip, imageContainer.m_numMips-1); bimg::TextureInfo ti; bimg::imageGetSize( &ti , uint16_t(imageContainer.m_width >>startLod) , uint16_t(imageContainer.m_height>>startLod) , uint16_t(imageContainer.m_depth >>startLod) , imageContainer.m_cubeMap , 1 < imageContainer.m_numMips , imageContainer.m_numLayers , imageContainer.m_format ); ti.numMips = bx::min<uint8_t>(imageContainer.m_numMips-startLod, ti.numMips); m_requestedFormat = uint8_t(imageContainer.m_format); m_textureFormat = uint8_t(getViableTextureFormat(imageContainer) ); const bool computeWrite = 0 != (_flags&BGFX_TEXTURE_COMPUTE_WRITE); const bool srgb = 0 != (_flags&BGFX_TEXTURE_SRGB); const bool msaaSample = 0 != (_flags&BGFX_TEXTURE_MSAA_SAMPLE); uint32_t msaaQuality = ( (_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT); msaaQuality = bx::uint32_satsub(msaaQuality, 1); msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality); GLenum target = msaaSample ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D; if (imageContainer.m_cubeMap) { target = GL_TEXTURE_CUBE_MAP; } else if (imageContainer.m_depth > 1) { target = GL_TEXTURE_3D; } const bool textureArray = 1 < ti.numLayers; if (textureArray) { switch (target) { case GL_TEXTURE_CUBE_MAP: target = GL_TEXTURE_CUBE_MAP_ARRAY; break; case GL_TEXTURE_2D_MULTISAMPLE: target = GL_TEXTURE_2D_MULTISAMPLE_ARRAY; break; default: target = GL_TEXTURE_2D_ARRAY; break; } } if (!init(target , ti.width , ti.height , textureArray ? ti.numLayers : ti.depth , ti.numMips , _flags ) ) { return; } m_numLayers = ti.numLayers; target = isCubeMap() ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : m_target ; const GLenum internalFmt = srgb ? s_textureFormat[m_textureFormat].m_internalFmtSrgb : s_textureFormat[m_textureFormat].m_internalFmt ; const bool swizzle = true && TextureFormat::BGRA8 == m_requestedFormat && !s_textureFormat[m_requestedFormat].m_supported && !s_renderGL->m_textureSwizzleSupport ; const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(m_requestedFormat) ); const bool convert = false || m_textureFormat != m_requestedFormat || swizzle ; BX_TRACE("Texture%-4s %3d: %s %s(requested: %s), layers %d, %dx%dx%d%s." , imageContainer.m_cubeMap ? "Cube" : (1 < imageContainer.m_depth ? "3D" : "2D") , this - s_renderGL->m_textures , getName( (TextureFormat::Enum)m_textureFormat) , srgb ? "+sRGB " : "" , getName( (TextureFormat::Enum)m_requestedFormat) , ti.numLayers , ti.width , ti.height , imageContainer.m_cubeMap ? 6 : (1 < imageContainer.m_depth ? imageContainer.m_depth : 0) , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : "" ); BX_WARN(!convert, "Texture %s%s%s from %s to %s." , swizzle ? "swizzle" : "" , swizzle&&convert ? " and " : "" , convert ? "convert" : "" , getName( (TextureFormat::Enum)m_requestedFormat) , getName( (TextureFormat::Enum)m_textureFormat) ); uint8_t* temp = NULL; if (convert) { temp = (uint8_t*)BX_ALLOC(g_allocator, ti.width*ti.height*4); } const uint16_t numSides = ti.numLayers * (imageContainer.m_cubeMap ? 6 : 1); for (uint16_t side = 0; side < numSides; ++side) { uint32_t width = ti.width; uint32_t height = ti.height; uint32_t depth = ti.depth; GLenum imageTarget = imageContainer.m_cubeMap && !textureArray ? target+side : target ; for (uint8_t lod = 0, num = ti.numMips; lod < num; ++lod) { width = bx::uint32_max(1, width); height = bx::uint32_max(1, height); depth = 1 < imageContainer.m_depth ? bx::uint32_max(1, depth) : side ; bimg::ImageMip mip; if (bimg::imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) ) { if (compressed && !convert) { GL_CHECK(compressedTexImage(imageTarget , lod , internalFmt , width , height , depth , 0 , mip.m_size , mip.m_data ) ); } else { const uint8_t* data = mip.m_data; if (convert) { imageDecodeToRgba8( g_allocator , temp , mip.m_data , mip.m_width , mip.m_height , mip.m_width*4 , mip.m_format ); data = temp; } GL_CHECK(texImage(imageTarget , msaaQuality , lod , internalFmt , width , height , depth , 0 , m_fmt , m_type , data ) ); } } else if (!computeWrite) { if (compressed) { uint32_t size = bx::max<uint32_t>(1, (width + 3)>>2) * bx::max<uint32_t>(1, (height + 3)>>2) * 4*4* bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) )/8 ; GL_CHECK(compressedTexImage(imageTarget , lod , internalFmt , width , height , depth , 0 , size , NULL ) ); } else { GL_CHECK(texImage(imageTarget , msaaQuality , lod , internalFmt , width , height , depth , 0 , m_fmt , m_type , NULL ) ); } } width >>= 1; height >>= 1; depth >>= 1; } } if (NULL != temp) { BX_FREE(g_allocator, temp); } } // HAX FOR MIPMAPS //GL_CHECK(glBindTexture(m_target, m_id)); m_numMips = calcNumMips(true, m_width, m_height); setSamplerState(uint32_t(m_flags), NULL); GL_CHECK(glGenerateMipmap(m_target)); //GL_CHECK(glBindTexture(m_target, 0)); GL_CHECK(glBindTexture(m_target, 0) ); } void TextureGL::destroy() { if (0 == (m_flags & BGFX_SAMPLER_INTERNAL_SHARED) && 0 != m_id) { GL_CHECK(glBindTexture(m_target, 0) ); GL_CHECK(glDeleteTextures(1, &m_id) ); m_id = 0; } if (0 != m_rbo) { GL_CHECK(glDeleteRenderbuffers(1, &m_rbo) ); m_rbo = 0; } } void TextureGL::overrideInternal(uintptr_t _ptr) { destroy(); m_flags |= BGFX_SAMPLER_INTERNAL_SHARED; m_id = (GLuint)_ptr; } void TextureGL::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) { const uint32_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) ); const uint32_t rectpitch = _rect.m_width*bpp/8; uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch; GL_CHECK(glBindTexture(m_target, m_id) ); GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) ); GLenum target = isCubeMap() ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : m_target ; const bool swizzle = true && TextureFormat::BGRA8 == m_requestedFormat && !s_textureFormat[m_requestedFormat].m_supported && !s_renderGL->m_textureSwizzleSupport ; const bool unpackRowLength = !!BGFX_CONFIG_RENDERER_OPENGL || s_extension[Extension::EXT_unpack_subimage].m_supported; const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(m_requestedFormat) ); const bool convert = false || (compressed && m_textureFormat != m_requestedFormat) || swizzle ; const uint32_t width = _rect.m_width; const uint32_t height = _rect.m_height; uint8_t* temp = NULL; if (convert || !unpackRowLength) { temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*height); } else if (unpackRowLength) { GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, srcpitch*8/bpp) ); } if (compressed) { const uint8_t* data = _mem->data; if (!unpackRowLength) { bimg::imageCopy(temp, width, height, 1, bpp, srcpitch, data); data = temp; } GL_CHECK(compressedTexSubImage(target+_side , _mip , _rect.m_x , _rect.m_y , _z , _rect.m_width , _rect.m_height , _depth , m_fmt , _mem->size , data ) ); } else { const uint8_t* data = _mem->data; if (convert) { bimg::imageDecodeToRgba8(g_allocator, temp, data, width, height, srcpitch, bimg::TextureFormat::Enum(m_requestedFormat) ); data = temp; srcpitch = rectpitch; } if (BX_IGNORE_C4127(true && !unpackRowLength && !convert) ) { bimg::imageCopy(temp, width, height, 1, bpp, srcpitch, data); data = temp; } GL_CHECK(texSubImage(target+_side , _mip , _rect.m_x , _rect.m_y , _z , _rect.m_width , _rect.m_height , _depth , m_fmt , m_type , data ) ); } if (!convert && unpackRowLength) { GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) ); } if (NULL != temp) { BX_FREE(g_allocator, temp); } } void TextureGL::setSamplerState(uint32_t _flags, const float _rgba[4]) { if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) && !s_textureFilter[m_textureFormat]) { // Force point sampling when texture format doesn't support linear sampling. _flags &= ~(0 | BGFX_SAMPLER_MIN_MASK | BGFX_SAMPLER_MAG_MASK | BGFX_SAMPLER_MIP_MASK ); _flags |= 0 | BGFX_SAMPLER_MIN_POINT | BGFX_SAMPLER_MAG_POINT | BGFX_SAMPLER_MIP_POINT ; } const uint32_t flags = (0 != (BGFX_SAMPLER_INTERNAL_DEFAULT & _flags) ? m_flags : _flags) & BGFX_SAMPLER_BITS_MASK; bool hasBorderColor = false; bx::HashMurmur2A murmur; murmur.begin(); murmur.add(flags); if (NULL != _rgba) { if (BGFX_SAMPLER_U_BORDER == (flags & BGFX_SAMPLER_U_BORDER) || BGFX_SAMPLER_V_BORDER == (flags & BGFX_SAMPLER_V_BORDER) || BGFX_SAMPLER_W_BORDER == (flags & BGFX_SAMPLER_W_BORDER) ) { murmur.add(_rgba, 16); hasBorderColor = true; } } uint32_t hash = murmur.end(); if (hash != m_currentSamplerHash) { const GLenum target = m_target == GL_TEXTURE_2D_MULTISAMPLE ? GL_TEXTURE_2D : m_target; const GLenum targetMsaa = m_target; const uint8_t numMips = m_numMips; GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_S, s_textureAddress[(flags&BGFX_SAMPLER_U_MASK)>>BGFX_SAMPLER_U_SHIFT]) ); GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_T, s_textureAddress[(flags&BGFX_SAMPLER_V_MASK)>>BGFX_SAMPLER_V_SHIFT]) ); if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_extension[Extension::APPLE_texture_max_level].m_supported) { GL_CHECK(glTexParameteri(targetMsaa, GL_TEXTURE_MAX_LEVEL, numMips-1) ); } if (target == GL_TEXTURE_3D) { GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_R, s_textureAddress[(flags&BGFX_SAMPLER_W_MASK)>>BGFX_SAMPLER_W_SHIFT]) ); } GLenum magFilter; GLenum minFilter; //getFilters(flags, 1 < numMips, magFilter, minFilter); getFilters(flags, true, magFilter, minFilter); // HAX GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter) ); GL_CHECK(glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter) ); if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) ) { GL_CHECK(glTexParameterf(target, GL_TEXTURE_LOD_BIAS, float(BGFX_CONFIG_MIP_LOD_BIAS) ) ); } if (s_renderGL->m_borderColorSupport && hasBorderColor) { GL_CHECK(glTexParameterfv(target, GL_TEXTURE_BORDER_COLOR, _rgba) ); } if (0 != (flags & (BGFX_SAMPLER_MIN_ANISOTROPIC|BGFX_SAMPLER_MAG_ANISOTROPIC) ) && 0.0f < s_renderGL->m_maxAnisotropy) { GL_CHECK(glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, s_renderGL->m_maxAnisotropy) ); } if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) || s_renderGL->m_shadowSamplersSupport) { const uint32_t cmpFunc = (flags&BGFX_SAMPLER_COMPARE_MASK)>>BGFX_SAMPLER_COMPARE_SHIFT; if (0 == cmpFunc) { GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_NONE) ); } else { GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) ); GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) ); } } m_currentSamplerHash = hash; } } void TextureGL::commit(uint32_t _stage, uint32_t _flags, const float _palette[][4]) { const uint32_t flags = 0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & _flags) ? _flags : uint32_t(m_flags) ; const uint32_t index = (flags & BGFX_SAMPLER_BORDER_COLOR_MASK) >> BGFX_SAMPLER_BORDER_COLOR_SHIFT; GL_CHECK(glActiveTexture(GL_TEXTURE0+_stage) ); GL_CHECK(glBindTexture(m_target, m_id) ); if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) ) { // GLES2 doesn't have support for sampler object. setSamplerState(flags, _palette[index]); } else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL < 31) ) { // In case that GL 2.1 sampler object is supported via extension. if (s_renderGL->m_samplerObjectSupport) { s_renderGL->setSamplerState(_stage, m_numMips, flags, _palette[index]); } else { setSamplerState(flags, _palette[index]); } } else { // Everything else has sampler object. s_renderGL->setSamplerState(_stage, m_numMips, flags, _palette[index]); } } void TextureGL::resolve(uint8_t _resolve) const { const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK); if (renderTarget && 1 < m_numMips && 0 != (_resolve & BGFX_RESOLVE_AUTO_GEN_MIPS) ) { GL_CHECK(glBindTexture(m_target, m_id) ); GL_CHECK(glGenerateMipmap(m_target) ); GL_CHECK(glBindTexture(m_target, 0) ); } } void strins(char* _str, const char* _insert) { size_t len = bx::strLen(_insert); bx::memMove(&_str[len], _str, bx::strLen(_str)+1); bx::memCopy(_str, _insert, len); } void ShaderGL::create(const Memory* _mem) { bx::MemoryReader reader(_mem->data, _mem->size); m_hash = bx::hash<bx::HashMurmur2A>(_mem->data, _mem->size); uint32_t magic; bx::read(&reader, magic); if (isShaderType(magic, 'C') ) { m_type = GL_COMPUTE_SHADER; } else if (isShaderType(magic, 'F') ) { m_type = GL_FRAGMENT_SHADER; } else if (isShaderType(magic, 'V') ) { m_type = GL_VERTEX_SHADER; } uint32_t hashIn; bx::read(&reader, hashIn); uint32_t hashOut; if (isShaderVerLess(magic, 6) ) { hashOut = hashIn; } else { bx::read(&reader, hashOut); } uint16_t count; bx::read(&reader, count); BX_TRACE("%s Shader consts %d" , getShaderTypeName(magic) , count ); for (uint32_t ii = 0; ii < count; ++ii) { uint8_t nameSize = 0; bx::read(&reader, nameSize); char name[256]; bx::read(&reader, &name, nameSize); name[nameSize] = '\0'; uint8_t type; bx::read(&reader, type); uint8_t num; bx::read(&reader, num); uint16_t regIndex; bx::read(&reader, regIndex); uint16_t regCount; bx::read(&reader, regCount); } uint32_t shaderSize; bx::read(&reader, shaderSize); m_id = glCreateShader(m_type); BX_WARN(0 != m_id, "Failed to create shader."); bx::StringView code( (const char*)reader.getDataPtr(), shaderSize); if (0 != m_id) { if (GL_COMPUTE_SHADER != m_type) { int32_t tempLen = code.getLength() + (4<<10); char* temp = (char*)alloca(tempLen); bx::StaticMemoryBlockWriter writer(temp, tempLen); bx::Error err; if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) ) { bx::write(&writer , "#define centroid\n" "#define flat\n" "#define noperspective\n" "#define smooth\n" ); bool usesDerivatives = s_extension[Extension::OES_standard_derivatives].m_supported && !bx::findIdentifierMatch(code, s_OES_standard_derivatives).isEmpty() ; const bool usesFragData = !bx::findIdentifierMatch(code, "gl_FragData").isEmpty(); const bool usesFragDepth = !bx::findIdentifierMatch(code, "gl_FragDepth").isEmpty(); const bool usesShadowSamplers = !bx::findIdentifierMatch(code, s_EXT_shadow_samplers).isEmpty(); const bool usesTextureLod = !bx::findIdentifierMatch(code, s_EXT_shader_texture_lod).isEmpty(); const bool usesFragmentOrdering = !bx::findIdentifierMatch(code, "beginFragmentShaderOrdering").isEmpty(); const bool usesTexture3D = true && s_extension[Extension::OES_texture_3D].m_supported && !bx::findIdentifierMatch(code, s_texture3D).isEmpty() ; if (usesDerivatives) { bx::write(&writer, "#extension GL_OES_standard_derivatives : enable\n"); } if (usesFragData) { BX_WARN(s_extension[Extension::EXT_draw_buffers ].m_supported || s_extension[Extension::WEBGL_draw_buffers].m_supported , "EXT_draw_buffers is used but not supported by GLES2 driver." ); bx::write(&writer, "#extension GL_EXT_draw_buffers : enable\n"); } bool insertFragDepth = false; if (usesFragDepth) { BX_WARN(s_extension[Extension::EXT_frag_depth].m_supported, "EXT_frag_depth is used but not supported by GLES2 driver."); if (s_extension[Extension::EXT_frag_depth].m_supported) { bx::write(&writer , "#extension GL_EXT_frag_depth : enable\n" "#define bgfx_FragDepth gl_FragDepthEXT\n" ); char str[128]; bx::snprintf(str, BX_COUNTOF(str), "%s float gl_FragDepthEXT;\n" , s_extension[Extension::OES_fragment_precision_high].m_supported ? "highp" : "mediump" ); bx::write(&writer, str); } else { insertFragDepth = true; } } if (usesShadowSamplers) { if (s_renderGL->m_shadowSamplersSupport) { bx::write(&writer , "#extension GL_EXT_shadow_samplers : enable\n" "#define shadow2D shadow2DEXT\n" "#define shadow2DProj shadow2DProjEXT\n" ); } else { bx::write(&writer , "#define sampler2DShadow sampler2D\n" "#define shadow2D(_sampler, _coord) step(_coord.z, texture2D(_sampler, _coord.xy).x)\n" "#define shadow2DProj(_sampler, _coord) step(_coord.z/_coord.w, texture2DProj(_sampler, _coord).x)\n" ); } } if (usesTexture3D) { bx::write(&writer, "#extension GL_OES_texture_3D : enable\n"); } if (usesTextureLod) { BX_WARN(s_extension[Extension::ARB_shader_texture_lod].m_supported || s_extension[Extension::EXT_shader_texture_lod].m_supported , "(ARB|EXT)_shader_texture_lod is used but not supported by GLES2 driver." ); if (s_extension[Extension::ARB_shader_texture_lod].m_supported) { bx::write(&writer , "#extension GL_ARB_shader_texture_lod : enable\n" "#define texture2DLod texture2DLodARB\n" "#define texture2DProjLod texture2DProjLodARB\n" "#define textureCubeLod textureCubeLodARB\n" "#define texture2DGrad texture2DGradARB\n" "#define texture2DProjGrad texture2DProjGradARB\n" "#define textureCubeGrad textureCubeGradARB\n" ); } else { if(s_extension[Extension::EXT_shader_texture_lod].m_supported) { bx::write(&writer , "#extension GL_EXT_shader_texture_lod : enable\n" "#define texture2DLod texture2DLodEXT\n" "#define texture2DProjLod texture2DProjLodEXT\n" "#define textureCubeLod textureCubeLodEXT\n" ); } else { bx::write(&writer , "#define texture2DLod(_sampler, _coord, _level) texture2D(_sampler, _coord)\n" "#define texture2DProjLod(_sampler, _coord, _level) texture2DProj(_sampler, _coord)\n" "#define textureCubeLod(_sampler, _coord, _level) textureCube(_sampler, _coord)\n" ); } } } if (usesFragmentOrdering) { if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported) { bx::write(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n"); } else { bx::write(&writer, "#define beginFragmentShaderOrdering()\n"); } } bx::write(&writer, &err, "precision %s float;\n" , m_type == GL_FRAGMENT_SHADER ? "mediump" : "highp" ); bx::write(&writer, code); bx::write(&writer, '\0'); if (insertFragDepth) { bx::StringView shader(temp); bx::StringView entry = bx::strFind(shader, "void main ()"); if (!entry.isEmpty() ) { entry.set(entry.getTerm(), shader.getTerm() ); bx::StringView brace = bx::strFind(entry, "{"); if (!brace.isEmpty() ) { bx::StringView block = bx::strFindBlock(bx::StringView(brace.getPtr(), shader.getTerm() ), '{', '}'); if (!block.isEmpty() ) { strins(const_cast<char*>(brace.getPtr()+1), "\n float bgfx_FragDepth = 0.0;\n"); } } } } // Replace all instances of gl_FragDepth with bgfx_FragDepth. for (bx::StringView fragDepth = bx::findIdentifierMatch(temp, "gl_FragDepth") ; !fragDepth.isEmpty() ; fragDepth = bx::findIdentifierMatch(fragDepth, "gl_FragDepth") ) { char* insert = const_cast<char*>(fragDepth.getPtr() ); strins(insert, "bg"); bx::memCopy(insert + 2, "fx", 2); } } else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL <= 21) ) { const bool usesTextureLod = true && s_extension[Extension::ARB_shader_texture_lod].m_supported && !bx::findIdentifierMatch(code, s_ARB_shader_texture_lod).isEmpty() ; const bool usesVertexID = true && !s_extension[Extension::EXT_gpu_shader4].m_supported && !bx::findIdentifierMatch(code, "gl_VertexID").isEmpty() ; const bool usesInstanceID = true && !s_extension[Extension::EXT_gpu_shader4].m_supported && !bx::findIdentifierMatch(code, "gl_InstanceID").isEmpty() ; const bool usesGpuShader4 = true && s_extension[Extension::EXT_gpu_shader4].m_supported && !bx::findIdentifierMatch(code, s_EXT_gpu_shader4).isEmpty() ; const bool usesGpuShader5 = !bx::findIdentifierMatch(code, s_ARB_gpu_shader5).isEmpty(); const bool usesIUsamplers = !bx::findIdentifierMatch(code, s_uisamplers).isEmpty(); const bool usesUint = !bx::findIdentifierMatch(code, s_uint).isEmpty(); const bool usesTexelFetch = !bx::findIdentifierMatch(code, s_texelFetch).isEmpty(); const bool usesTextureArray = !bx::findIdentifierMatch(code, s_textureArray).isEmpty(); const bool usesTexture3D = !bx::findIdentifierMatch(code, s_texture3D).isEmpty(); const bool usesTextureMS = !bx::findIdentifierMatch(code, s_ARB_texture_multisample).isEmpty(); const bool usesPacking = !bx::findIdentifierMatch(code, s_ARB_shading_language_packing).isEmpty(); const bool usesInterpQ = !bx::findIdentifierMatch(code, s_intepolationQualifier).isEmpty(); uint32_t version = BX_ENABLED(BX_PLATFORM_OSX) ? 120 : usesTextureArray || usesTexture3D || usesIUsamplers || usesVertexID || usesUint || usesTexelFetch || usesGpuShader5 || usesInterpQ ? 130 : usesTextureLod ? 120 : 120 ; version = 0 == bx::strCmp(code, "#version 430", 12) ? 430 : version; bx::write(&writer, &err, "#version %d\n", version); if (430 > version && usesTextureLod) { if (m_type == GL_FRAGMENT_SHADER) { bx::write(&writer , "#extension GL_ARB_shader_texture_lod : enable\n" "#define texture2DGrad texture2DGradARB\n" "#define texture2DProjGrad texture2DProjGradARB\n" "#define textureCubeGrad textureCubeGradARB\n" ); } } if (usesInstanceID) { bx::write(&writer, "#extension GL_ARB_draw_instanced : enable\n"); } if (usesGpuShader4) { bx::write(&writer, "#extension GL_EXT_gpu_shader4 : enable\n"); } if (usesGpuShader5) { bx::write(&writer, "#extension GL_ARB_gpu_shader5 : enable\n"); } if (usesPacking) { bx::write(&writer, "#extension GL_ARB_shading_language_packing : enable\n"); } if (usesTextureMS) { bx::write(&writer, "#extension GL_ARB_texture_multisample : enable\n"); } if (usesTextureArray) { bx::write(&writer, "#extension GL_EXT_texture_array : enable\n"); if (BX_ENABLED(BX_PLATFORM_OSX) ) { bx::write(&writer, "#define texture2DArrayLod texture2DArray\n"); } else { bx::write(&writer, "#define texture2DArrayLodEXT texture2DArrayLod\n"); } } if (usesTexture3D) { bx::write(&writer, "#define texture3DEXT texture3D\n"); if (BX_ENABLED(BX_PLATFORM_OSX) ) { bx::write(&writer, "#define texture3DLodEXT texture3D\n"); } else { bx::write(&writer, "#define texture3DLodEXT texture3DLod\n"); } } if (130 <= version) { if (430 > version) { if (m_type == GL_FRAGMENT_SHADER) { bx::write(&writer, "#define varying in\n"); } else { bx::write(&writer, "#define attribute in\n"); bx::write(&writer, "#define varying out\n"); } } uint32_t fragData = 0; if (!bx::findIdentifierMatch(code, "gl_FragData").isEmpty() ) { for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii) { char tmpFragData[16]; bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii); fragData = bx::uint32_max(fragData, bx::strFind(code, tmpFragData).isEmpty() ? 0 : ii+1); } BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!"); } if (0 != fragData) { bx::write(&writer, &err, "out vec4 bgfx_FragData[%d];\n", fragData); bx::write(&writer, "#define gl_FragData bgfx_FragData\n"); } else if (!bx::findIdentifierMatch(code, "gl_FragColor").isEmpty() ) { bx::write(&writer, "out vec4 bgfx_FragColor;\n"); bx::write(&writer, "#define gl_FragColor bgfx_FragColor\n"); } } else { if (m_type == GL_FRAGMENT_SHADER) { bx::write(&writer, "#define in varying\n"); } else { bx::write(&writer , "#define in attribute\n" "#define out varying\n" ); } } bx::write(&writer, "#define lowp\n" "#define mediump\n" "#define highp\n" ); if (!usesInterpQ) { bx::write(&writer, "#define centroid\n" "#define flat\n" "#define noperspective\n" "#define smooth\n" ); } if (version == 430) { int32_t verLen = bx::strLen("#version 430\n"); bx::write(&writer, code.getPtr()+verLen, code.getLength()-verLen); } else { bx::write(&writer, code); } bx::write(&writer, '\0'); } else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 31) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) ) { if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) ) { bx::write(&writer, &err , "#version 300 es\n" "precision %s float;\n" , m_type == GL_FRAGMENT_SHADER ? "mediump" : "highp" ); } else { bx::write(&writer, "#version 140\n"); } bx::write(&writer , "#define texture2DLod textureLod\n" "#define texture3DLod textureLod\n" "#define textureCubeLod textureLod\n" "#define texture2DGrad textureGrad\n" "#define texture3DGrad textureGrad\n" "#define textureCubeGrad textureGrad\n" ); if (m_type == GL_FRAGMENT_SHADER) { bx::write(&writer , "#define varying in\n" "#define texture2D texture\n" "#define texture2DProj textureProj\n" ); if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) ) { bx::write(&writer, "#define shadow2D(_sampler, _coord) vec2(textureProj(_sampler, vec4(_coord, 1.0) ) )\n"); bx::write(&writer, "#define shadow2DProj(_sampler, _coord) vec2(textureProj(_sampler, _coord) ) )\n"); } else { bx::write(&writer, "#define shadow2D(_sampler, _coord) (textureProj(_sampler, vec4(_coord, 1.0) ) )\n"); bx::write(&writer, "#define shadow2DProj(_sampler, _coord) (textureProj(_sampler, _coord) ) )\n"); } bx::write(&writer, "#define texture3D texture\n"); bx::write(&writer, "#define textureCube texture\n"); uint32_t fragData = 0; if (!bx::findIdentifierMatch(code, "gl_FragData").isEmpty() ) { for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii) { char tmpFragData[16]; bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii); fragData = bx::max(fragData, bx::strFind(code, tmpFragData).isEmpty() ? 0 : ii+1); } BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!"); } if (!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering").isEmpty() ) { if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported) { bx::write(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n"); } else { bx::write(&writer, "#define beginFragmentShaderOrdering()\n"); } } if (!bx::findIdentifierMatch(code, s_ARB_texture_multisample).isEmpty() ) { bx::write(&writer, "#extension GL_ARB_texture_multisample : enable\n"); } if (0 != fragData) { bx::write(&writer, &err, "out vec4 bgfx_FragData[%d];\n", fragData); bx::write(&writer, "#define gl_FragData bgfx_FragData\n"); } else { bx::write(&writer , "out vec4 bgfx_FragColor;\n" "#define gl_FragColor bgfx_FragColor\n" ); } } else { bx::write(&writer , "#define attribute in\n" "#define varying out\n" ); } if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) ) { bx::write(&writer , "#define lowp\n" "#define mediump\n" "#define highp\n" ); } bx::write(&writer, code.getPtr(), code.getLength() ); bx::write(&writer, '\0'); } code.set(temp); } else // GL_COMPUTE_SHADER { int32_t codeLen = (int32_t)bx::strLen(code); int32_t tempLen = codeLen + (4<<10); char* temp = (char*)alloca(tempLen); bx::StaticMemoryBlockWriter writer(temp, tempLen); bx::write(&writer , "#version 430\n" "#define texture2DLod textureLod\n" "#define texture2DLodOffset textureLodOffset\n" "#define texture2DArrayLod textureLod\n" "#define texture2DArrayLodOffset textureLodOffset\n" "#define texture3DLod textureLod\n" "#define textureCubeLod textureLod\n" "#define texture2DGrad textureGrad\n" "#define texture3DGrad textureGrad\n" "#define textureCubeGrad textureGrad\n" ); int32_t verLen = bx::strLen("#version 430\n"); bx::write(&writer, code.getPtr()+verLen, codeLen-verLen); bx::write(&writer, '\0'); code = temp; } GL_CHECK(glShaderSource(m_id, 1, (const GLchar**)&code, NULL) ); GL_CHECK(glCompileShader(m_id) ); GLint compiled = 0; GL_CHECK(glGetShaderiv(m_id, GL_COMPILE_STATUS, &compiled) ); if (0 == compiled) { LineReader lineReader(code); bx::Error err; for (int32_t line = 1; err.isOk(); ++line) { char str[4096]; int32_t len = bx::read(&lineReader, str, BX_COUNTOF(str)-1, &err); if (err.isOk() ) { str[len] = '\0'; bx::StringView eol = bx::strFindEol(str); if (eol.getPtr() != str) { *const_cast<char*>(eol.getPtr() ) = '\0'; } BX_TRACE("%3d %s", line, str); } } GLsizei len; char log[1024]; GL_CHECK(glGetShaderInfoLog(m_id, sizeof(log), &len, log) ); BX_TRACE("Failed to compile shader. %d: %s", compiled, log); GL_CHECK(glDeleteShader(m_id) ); m_id = 0; BGFX_FATAL(false, bgfx::Fatal::InvalidShader, "Failed to compile shader."); } else if (BX_ENABLED(BGFX_CONFIG_DEBUG) && s_extension[Extension::ANGLE_translated_shader_source].m_supported && NULL != glGetTranslatedShaderSourceANGLE) { GLsizei len; GL_CHECK(glGetShaderiv(m_id, GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE, &len) ); char* source = (char*)alloca(len); GL_CHECK(glGetTranslatedShaderSourceANGLE(m_id, len, &len, source) ); BX_TRACE("ANGLE source (len: %d):\n%s\n####", len, source); } } } void ShaderGL::destroy() { if (0 != m_id) { GL_CHECK(glDeleteShader(m_id) ); m_id = 0; } } void FrameBufferGL::create(uint8_t _num, const Attachment* _attachment) { GL_CHECK(glGenFramebuffers(1, &m_fbo[0]) ); m_denseIdx = UINT16_MAX; m_numTh = _num; bx::memCopy(m_attachment, _attachment, _num*sizeof(Attachment) ); m_needPresent = false; postReset(); } void FrameBufferGL::postReset() { if (0 != m_fbo[0]) { GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) ); bool needResolve = false; GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS]; uint32_t colorIdx = 0; for (uint32_t ii = 0; ii < m_numTh; ++ii) { const Attachment& at = m_attachment[ii]; if (isValid(at.handle) ) { const TextureGL& texture = s_renderGL->m_textures[at.handle.idx]; if (0 == colorIdx) { m_width = bx::uint32_max(texture.m_width >> at.mip, 1); m_height = bx::uint32_max(texture.m_height >> at.mip, 1); } GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx; bimg::TextureFormat::Enum format = bimg::TextureFormat::Enum(texture.m_textureFormat); if (bimg::isDepth(format) ) { const bimg::ImageBlockInfo& info = bimg::getBlockInfo(format); if (0 < info.stencilBits) { attachment = GL_DEPTH_STENCIL_ATTACHMENT; } else if (0 == info.depthBits) { attachment = GL_STENCIL_ATTACHMENT; } else { attachment = GL_DEPTH_ATTACHMENT; } } else if (Access::Write == at.access) { buffers[colorIdx] = attachment; ++colorIdx; } if (0 != texture.m_rbo) { #if !(BGFX_CONFIG_RENDERER_OPENGL >= 30 || BGFX_CONFIG_RENDERER_OPENGLES >= 30) if (GL_DEPTH_STENCIL_ATTACHMENT == attachment) { GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER , GL_DEPTH_ATTACHMENT , GL_RENDERBUFFER , texture.m_rbo ) ); GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER , GL_STENCIL_ATTACHMENT , GL_RENDERBUFFER , texture.m_rbo ) ); } else #endif { GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER , attachment , GL_RENDERBUFFER , texture.m_rbo ) ); } } else { if (1 < texture.m_numLayers && !texture.isCubeMap()) { GL_CHECK(glFramebufferTextureLayer(GL_FRAMEBUFFER , attachment , texture.m_id , at.mip , at.layer ) ); } else { GLenum target = texture.isCubeMap() ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + at.layer : texture.m_target ; GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER , attachment , target , texture.m_id , at.mip ) ); } } needResolve |= (0 != texture.m_rbo) && (0 != texture.m_id); } } m_num = uint8_t(colorIdx); if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 31) ) { if (0 == colorIdx) { if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) ) { // When only depth is attached disable draw buffer to avoid // GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER. GL_CHECK(glDrawBuffer(GL_NONE) ); } } else { GL_CHECK(glDrawBuffers(colorIdx, buffers) ); } // Disable read buffer to avoid GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER. GL_CHECK(glReadBuffer(GL_NONE) ); } frameBufferValidate(); if (needResolve) { GL_CHECK(glGenFramebuffers(1, &m_fbo[1]) ); GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[1]) ); colorIdx = 0; for (uint32_t ii = 0; ii < m_numTh; ++ii) { const Attachment& at = m_attachment[ii]; if (isValid(at.handle) ) { const TextureGL& texture = s_renderGL->m_textures[at.handle.idx]; if (0 != texture.m_id) { GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx; if (!bimg::isDepth(bimg::TextureFormat::Enum(texture.m_textureFormat) ) ) { ++colorIdx; GLenum target = texture.isCubeMap() ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + at.layer : texture.m_target ; GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER , attachment , target , texture.m_id , at.mip ) ); } } } } frameBufferValidate(); } GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) ); } } void FrameBufferGL::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat) { BX_UNUSED(_format, _depthFormat); m_swapChain = s_renderGL->m_glctx.createSwapChain(_nwh); m_width = _width; m_height = _height; m_numTh = 0; m_denseIdx = _denseIdx; m_needPresent = false; } uint16_t FrameBufferGL::destroy() { if (0 != m_num) { GL_CHECK(glDeleteFramebuffers(0 == m_fbo[1] ? 1 : 2, m_fbo) ); m_num = 0; } if (NULL != m_swapChain) { s_renderGL->m_glctx.destroySwapChain(m_swapChain); m_swapChain = NULL; } bx::memSet(m_fbo, 0, sizeof(m_fbo) ); uint16_t denseIdx = m_denseIdx; m_denseIdx = UINT16_MAX; m_needPresent = false; m_numTh = 0; return denseIdx; } void FrameBufferGL::resolve() { if (0 != m_fbo[1]) { uint32_t colorIdx = 0; for (uint32_t ii = 0; ii < m_numTh; ++ii) { const Attachment& at = m_attachment[ii]; if (isValid(at.handle) ) { const TextureGL& texture = s_renderGL->m_textures[at.handle.idx]; bimg::TextureFormat::Enum format = bimg::TextureFormat::Enum(texture.m_textureFormat); if (!bimg::isDepth(format) ) { GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) ); GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo[1]) ); GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0 + colorIdx) ); GL_CHECK(glDrawBuffer(GL_COLOR_ATTACHMENT0 + colorIdx) ); colorIdx++; GL_CHECK(glBlitFramebuffer(0 , 0 , m_width , m_height , 0 , 0 , m_width , m_height , GL_COLOR_BUFFER_BIT , GL_LINEAR ) ); } } } GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) ); GL_CHECK(glReadBuffer(GL_NONE) ); GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) ); } for (uint32_t ii = 0; ii < m_numTh; ++ii) { const Attachment& at = m_attachment[ii]; if (isValid(at.handle) ) { const TextureGL& texture = s_renderGL->m_textures[at.handle.idx]; texture.resolve(at.resolve); } } } void FrameBufferGL::discard(uint16_t _flags) { GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS+2]; uint32_t idx = 0; if (BGFX_CLEAR_NONE != (_flags & BGFX_CLEAR_DISCARD_COLOR_MASK) ) { for (uint32_t ii = 0, num = m_num; ii < num; ++ii) { if (BGFX_CLEAR_NONE != (_flags & (BGFX_CLEAR_DISCARD_COLOR_0<<ii) ) ) { buffers[idx++] = GL_COLOR_ATTACHMENT0 + ii; } } } uint32_t dsFlags = _flags & (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL); if (BGFX_CLEAR_NONE != dsFlags) { if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) && (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL) == dsFlags) { buffers[idx++] = GL_DEPTH_STENCIL_ATTACHMENT; } else if (BGFX_CLEAR_DISCARD_DEPTH == dsFlags) { buffers[idx++] = GL_DEPTH_ATTACHMENT; } else if (BGFX_CLEAR_DISCARD_STENCIL == dsFlags) { buffers[idx++] = GL_STENCIL_ATTACHMENT; } } GL_CHECK(glInvalidateFramebuffer(GL_FRAMEBUFFER, idx, buffers) ); } void FrameBufferGL::set() { for(uint32_t ii = 0; ii < m_numTh; ++ii) { const Attachment& at = m_attachment[ii]; if (at.access == Access::Write) { continue; } if (isValid(at.handle) ) { const TextureGL& texture = s_renderGL->m_textures[at.handle.idx]; if(0 != (texture.m_flags&BGFX_TEXTURE_COMPUTE_WRITE)) { GL_CHECK(glBindImageTexture(ii , texture.m_id , at.mip , GL_FALSE //texture.isLayered() ? GL_TRUE : GL_FALSE , at.layer , s_access[Access::ReadWrite] , s_imageFormat[texture.m_textureFormat]) ); } } } } void OcclusionQueryGL::create() { for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii) { Query& query = m_query[ii]; GL_CHECK(glGenQueries(1, &query.m_id) ); } } void OcclusionQueryGL::destroy() { for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii) { Query& query = m_query[ii]; GL_CHECK(glDeleteQueries(1, &query.m_id) ); } } void OcclusionQueryGL::begin(Frame* _render, OcclusionQueryHandle _handle) { while (0 == m_control.reserve(1) ) { resolve(_render, true); } Query& query = m_query[m_control.m_current]; GL_CHECK(glBeginQuery(GL_SAMPLES_PASSED, query.m_id) ); query.m_handle = _handle; } void OcclusionQueryGL::end() { GL_CHECK(glEndQuery(GL_SAMPLES_PASSED) ); m_control.commit(1); } void OcclusionQueryGL::resolve(Frame* _render, bool _wait) { while (0 != m_control.available() ) { Query& query = m_query[m_control.m_read]; if (isValid(query.m_handle) ) { int32_t result; if (!_wait) { GL_CHECK(glGetQueryObjectiv(query.m_id, GL_QUERY_RESULT_AVAILABLE, &result) ); if (!result) { break; } } GL_CHECK(glGetQueryObjectiv(query.m_id, GL_QUERY_RESULT, &result) ); _render->m_occlusion[query.m_handle.idx] = int32_t(result); } m_control.consume(1); } } void OcclusionQueryGL::invalidate(OcclusionQueryHandle _handle) { const uint32_t size = m_control.m_size; for (uint32_t ii = 0, num = m_control.available(); ii < num; ++ii) { Query& query = m_query[(m_control.m_read + ii) % size]; if (query.m_handle.idx == _handle.idx) { query.m_handle.idx = bgfx::kInvalidHandle; } } } void RendererContextGL::submitBlit(BlitState& _bs, uint16_t _view) { if (m_blitSupported) { while (_bs.hasItem(_view) ) { const BlitItem& bi = _bs.advance(); const TextureGL& src = m_textures[bi.m_src.idx]; const TextureGL& dst = m_textures[bi.m_dst.idx]; uint32_t srcWidth = bx::uint32_min(src.m_width, bi.m_srcX + bi.m_width) - bi.m_srcX; uint32_t srcHeight = bx::uint32_min(src.m_height, bi.m_srcY + bi.m_height) - bi.m_srcY; uint32_t srcDepth = bx::uint32_min(src.m_depth, bi.m_srcZ + bi.m_depth) - bi.m_srcZ; uint32_t dstWidth = bx::uint32_min(dst.m_width, bi.m_dstX + bi.m_width) - bi.m_dstX; uint32_t dstHeight = bx::uint32_min(dst.m_height, bi.m_dstY + bi.m_height) - bi.m_dstY; uint32_t dstDepth = bx::uint32_min(dst.m_depth, bi.m_dstZ + bi.m_depth) - bi.m_dstZ; uint32_t width = bx::uint32_min(srcWidth, dstWidth); uint32_t height = bx::uint32_min(srcHeight, dstHeight); uint32_t depth = bx::uint32_min(srcDepth, dstDepth); GL_CHECK(glCopyImageSubData(src.m_id , src.m_target , bi.m_srcMip , bi.m_srcX , bi.m_srcY , bi.m_srcZ , dst.m_id , dst.m_target , bi.m_dstMip , bi.m_dstX , bi.m_dstY , bi.m_dstZ , width , height , bx::uint32_imax(depth, 1) ) ); } } } void RendererContextGL::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) { if (_render->m_capture) { renderDocTriggerCapture(); } m_glctx.makeCurrent(NULL); BGFX_GL_PROFILER_BEGIN_LITERAL("rendererSubmit", kColorView); if (1 < m_numWindows && m_vaoSupport) { m_vaoSupport = false; GL_CHECK(glBindVertexArray(0) ); GL_CHECK(glDeleteVertexArrays(1, &m_vao) ); m_vao = 0; } const GLuint defaultVao = m_vao; if (0 != defaultVao) { GL_CHECK(glBindVertexArray(defaultVao) ); } GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) ); GL_CHECK(glFrontFace(GL_CW) ); updateResolution(_render->m_resolution); int64_t timeBegin = bx::getHPCounter(); int64_t captureElapsed = 0; uint32_t frameQueryIdx = UINT32_MAX; if (m_timerQuerySupport && !BX_ENABLED(BX_PLATFORM_OSX) ) { frameQueryIdx = m_gpuTimer.begin(BGFX_CONFIG_MAX_VIEWS); } if (0 < _render->m_iboffset) { BGFX_PROFILER_SCOPE("bgfx/Update transient index buffer", kColorResource); TransientIndexBuffer* ib = _render->m_transientIb; m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data, true); } if (0 < _render->m_vboffset) { BGFX_PROFILER_SCOPE("bgfx/Update transient vertex buffer", kColorResource); TransientVertexBuffer* vb = _render->m_transientVb; m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data, true); } _render->sort(); RenderDraw currentState; currentState.clear(); currentState.m_stateFlags = BGFX_STATE_NONE; currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE); RenderBind currentBind; currentBind.clear(); static ViewState viewState; viewState.reset(_render); ProgramHandle currentProgram = BGFX_INVALID_HANDLE; ProgramHandle boundProgram = BGFX_INVALID_HANDLE; SortKey key; uint16_t view = UINT16_MAX; FrameBufferHandle fbh = { BGFX_CONFIG_MAX_FRAME_BUFFERS }; BlitState bs(_render); int32_t resolutionHeight = _render->m_resolution.height; uint32_t blendFactor = 0; uint8_t primIndex; { const uint64_t pt = 0; primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT); } PrimInfo prim = s_primInfo[primIndex]; GL_CHECK(glPolygonMode(GL_FRONT_AND_BACK , _render->m_debug&BGFX_DEBUG_WIREFRAME ? GL_LINE : GL_FILL ) ); bool wasCompute = false; bool viewHasScissor = false; Rect viewScissorRect; viewScissorRect.clear(); uint16_t discardFlags = BGFX_CLEAR_NONE; const bool blendIndependentSupported = s_extension[Extension::ARB_draw_buffers_blend].m_supported; const bool computeSupported = false || (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && s_extension[Extension::ARB_compute_shader].m_supported) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) ; const uint32_t maxComputeBindings = g_caps.limits.maxComputeBindings; uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {}; uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {}; uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {}; uint32_t statsNumIndices = 0; uint32_t statsKeyType[2] = {}; Profiler<TimerQueryGL> profiler( _render , m_gpuTimer , s_viewName , m_timerQuerySupport && !BX_ENABLED(BX_PLATFORM_OSX) ); if (m_occlusionQuerySupport) { m_occlusionQuery.resolve(_render); } if (0 == (_render->m_debug&BGFX_DEBUG_IFH) ) { GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) ); viewState.m_rect = _render->m_view[0].m_rect; int32_t numItems = _render->m_numRenderItems; for (int32_t item = 0; item < numItems;) { const uint64_t encodedKey = _render->m_sortKeys[item]; const bool isCompute = key.decode(encodedKey, _render->m_viewRemap); statsKeyType[isCompute]++; const bool viewChanged = 0 || key.m_view != view || item == numItems ; const uint32_t itemIdx = _render->m_sortValues[item]; const RenderItem& renderItem = _render->m_renderItem[itemIdx]; const RenderBind& renderBind = _render->m_renderItemBind[itemIdx]; ++item; if (viewChanged) { view = key.m_view; currentProgram = BGFX_INVALID_HANDLE; if (item > 1) { profiler.end(); } BGFX_GL_PROFILER_END(); if (_render->m_view[view].m_fbh.idx != fbh.idx) { fbh = _render->m_view[view].m_fbh; resolutionHeight = _render->m_resolution.height; resolutionHeight = setFrameBuffer(fbh, resolutionHeight, discardFlags); } setViewType(view, " "); BGFX_GL_PROFILER_BEGIN(view, kColorView); profiler.begin(view); viewState.m_rect = _render->m_view[view].m_rect; const Rect& scissorRect = _render->m_view[view].m_scissor; viewHasScissor = !scissorRect.isZero(); viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect; GL_CHECK(glViewport(viewState.m_rect.m_x , resolutionHeight-viewState.m_rect.m_height-viewState.m_rect.m_y , viewState.m_rect.m_width , viewState.m_rect.m_height ) ); Clear& clear = _render->m_view[view].m_clear; discardFlags = clear.m_flags & BGFX_CLEAR_DISCARD_MASK; if (BGFX_CLEAR_NONE != (clear.m_flags & BGFX_CLEAR_MASK) ) { clearQuad(_clearQuad, viewState.m_rect, clear, resolutionHeight, _render->m_colorPalette); } GL_CHECK(glDisable(GL_STENCIL_TEST) ); GL_CHECK(glEnable(GL_DEPTH_TEST) ); GL_CHECK(glDepthFunc(GL_LESS) ); GL_CHECK(glEnable(GL_CULL_FACE) ); GL_CHECK(glDisable(GL_BLEND) ); submitBlit(bs, view); } if (isCompute) { if (!wasCompute) { wasCompute = true; setViewType(view, "C"); BGFX_GL_PROFILER_END(); BGFX_GL_PROFILER_BEGIN(view, kColorCompute); } if (computeSupported) { const RenderCompute& compute = renderItem.compute; ProgramGL& program = m_program[key.m_program.idx]; GL_CHECK(glUseProgram(program.m_id) ); GLbitfield barrier = 0; for (uint32_t ii = 0; ii < maxComputeBindings; ++ii) { const Binding& bind = renderBind.m_bind[ii]; if (kInvalidHandle != bind.m_idx) { switch (bind.m_type) { case Binding::Texture: { TextureGL& texture = m_textures[bind.m_idx]; texture.commit(ii, bind.m_samplerFlags, _render->m_colorPalette); } break; case Binding::Image: { const TextureGL& texture = m_textures[bind.m_idx]; GL_CHECK(glBindImageTexture(ii , texture.m_id , bind.m_mip , texture.isCubeMap() || texture.m_target == GL_TEXTURE_2D_ARRAY ? GL_TRUE : GL_FALSE , 0 , s_access[bind.m_access] , s_imageFormat[bind.m_format]) ); barrier |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; } break; case Binding::IndexBuffer: { const IndexBufferGL& buffer = m_indexBuffers[bind.m_idx]; GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) ); barrier |= GL_SHADER_STORAGE_BARRIER_BIT; } break; case Binding::VertexBuffer: { const VertexBufferGL& buffer = m_vertexBuffers[bind.m_idx]; GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) ); barrier |= GL_SHADER_STORAGE_BARRIER_BIT; } break; } } } if (0 != barrier) { bool constantsChanged = compute.m_uniformBegin < compute.m_uniformEnd; rendererUpdateUniforms(this, _render->m_uniformBuffer[compute.m_uniformIdx], compute.m_uniformBegin, compute.m_uniformEnd); if (constantsChanged && NULL != program.m_constantBuffer) { commit(*program.m_constantBuffer); } viewState.setPredefined<1>(this, view, program, _render, compute); if (isValid(compute.m_indirectBuffer) ) { barrier |= GL_COMMAND_BARRIER_BIT; const VertexBufferGL& vb = m_vertexBuffers[compute.m_indirectBuffer.idx]; if (currentState.m_indirectBuffer.idx != compute.m_indirectBuffer.idx) { currentState.m_indirectBuffer = compute.m_indirectBuffer; GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, vb.m_id) ); } uint32_t numDrawIndirect = UINT16_MAX == compute.m_numIndirect ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE : compute.m_numIndirect ; uintptr_t args = compute.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE; for (uint32_t ii = 0; ii < numDrawIndirect; ++ii) { GL_CHECK(glDispatchComputeIndirect( (GLintptr)args) ); args += BGFX_CONFIG_DRAW_INDIRECT_STRIDE; } } else { if (isValid(currentState.m_indirectBuffer) ) { currentState.m_indirectBuffer.idx = kInvalidHandle; GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0) ); } GL_CHECK(glDispatchCompute(compute.m_numX, compute.m_numY, compute.m_numZ) ); } GL_CHECK(glMemoryBarrier(barrier) ); } } continue; } bool resetState = viewChanged || wasCompute; if (wasCompute) { wasCompute = false; setViewType(view, " "); BGFX_GL_PROFILER_END(); BGFX_GL_PROFILER_BEGIN(view, kColorDraw); } const RenderDraw& draw = renderItem.draw; const bool hasOcclusionQuery = 0 != (draw.m_stateFlags & BGFX_STATE_INTERNAL_OCCLUSION_QUERY); { const bool occluded = true && isValid(draw.m_occlusionQuery) && !hasOcclusionQuery && !isVisible(_render, draw.m_occlusionQuery, 0 != (draw.m_submitFlags&BGFX_SUBMIT_INTERNAL_OCCLUSION_VISIBLE) ) ; if (occluded || _render->m_frameCache.isZeroArea(viewScissorRect, draw.m_scissor) ) { if (resetState) { currentState.clear(); currentState.m_scissor = !draw.m_scissor; currentBind.clear(); } continue; } } const uint64_t newFlags = draw.m_stateFlags; uint64_t changedFlags = currentState.m_stateFlags ^ draw.m_stateFlags; currentState.m_stateFlags = newFlags; const uint64_t newStencil = draw.m_stencil; uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil; currentState.m_stencil = newStencil; if (resetState) { currentState.clear(); currentState.m_scissor = !draw.m_scissor; changedFlags = BGFX_STATE_MASK; changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK); currentState.m_stateFlags = newFlags; currentState.m_stencil = newStencil; currentBind.clear(); } uint16_t scissor = draw.m_scissor; if (currentState.m_scissor != scissor) { currentState.m_scissor = scissor; if (UINT16_MAX == scissor) { if (viewHasScissor) { GL_CHECK(glEnable(GL_SCISSOR_TEST) ); GL_CHECK(glScissor(viewScissorRect.m_x , resolutionHeight-viewScissorRect.m_height-viewScissorRect.m_y , viewScissorRect.m_width , viewScissorRect.m_height ) ); } else { GL_CHECK(glDisable(GL_SCISSOR_TEST) ); } } else { Rect scissorRect; scissorRect.setIntersect(viewScissorRect, _render->m_frameCache.m_rectCache.m_cache[scissor]); GL_CHECK(glEnable(GL_SCISSOR_TEST) ); GL_CHECK(glScissor(scissorRect.m_x , resolutionHeight-scissorRect.m_height-scissorRect.m_y , scissorRect.m_width , scissorRect.m_height ) ); } } if (0 != changedStencil) { if (0 != newStencil) { GL_CHECK(glEnable(GL_STENCIL_TEST) ); uint32_t bstencil = unpackStencil(1, newStencil); uint8_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != unpackStencil(0, newStencil); // uint32_t bchanged = unpackStencil(1, changedStencil); // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged) // { // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT; // GL_CHECK(glStencilMask(wmask) ); // } for (uint8_t ii = 0, num = frontAndBack+1; ii < num; ++ii) { uint32_t stencil = unpackStencil(ii, newStencil); uint32_t changed = unpackStencil(ii, changedStencil); GLenum face = s_stencilFace[frontAndBack+ii]; if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed) { GLint ref = (stencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT; GLint mask = (stencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT; uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT; GL_CHECK(glStencilFuncSeparate(face, s_cmpFunc[func], ref, mask) ); } if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed) { uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT; uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT; uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT; GL_CHECK(glStencilOpSeparate(face, s_stencilOp[sfail], s_stencilOp[zfail], s_stencilOp[zpass]) ); } } } else { GL_CHECK(glDisable(GL_STENCIL_TEST) ); } } if ( (0 | BGFX_STATE_CULL_MASK | BGFX_STATE_WRITE_Z | BGFX_STATE_DEPTH_TEST_MASK | BGFX_STATE_WRITE_RGB | BGFX_STATE_WRITE_A | BGFX_STATE_BLEND_MASK | BGFX_STATE_BLEND_EQUATION_MASK | BGFX_STATE_ALPHA_REF_MASK | BGFX_STATE_PT_MASK | BGFX_STATE_POINT_SIZE_MASK | BGFX_STATE_MSAA | BGFX_STATE_LINEAA | BGFX_STATE_CONSERVATIVE_RASTER ) & changedFlags) { if (BGFX_STATE_CULL_MASK & changedFlags) { if (BGFX_STATE_CULL_CCW & newFlags) { GL_CHECK(glEnable(GL_CULL_FACE) ); GL_CHECK(glCullFace(GL_BACK) ); } else if (BGFX_STATE_CULL_CW & newFlags) { GL_CHECK(glEnable(GL_CULL_FACE) ); GL_CHECK(glCullFace(GL_FRONT) ); } else { GL_CHECK(glDisable(GL_CULL_FACE) ); } } if (BGFX_STATE_WRITE_Z & changedFlags) { GL_CHECK(glDepthMask(!!(BGFX_STATE_WRITE_Z & newFlags) ) ); } if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags) { uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT; if (0 != func) { GL_CHECK(glEnable(GL_DEPTH_TEST) ); GL_CHECK(glDepthFunc(s_cmpFunc[func]) ); } else { if (BGFX_STATE_WRITE_Z & newFlags) { GL_CHECK(glEnable(GL_DEPTH_TEST) ); GL_CHECK(glDepthFunc(GL_ALWAYS) ); } else { GL_CHECK(glDisable(GL_DEPTH_TEST) ); } } } if (BGFX_STATE_ALPHA_REF_MASK & changedFlags) { uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT; viewState.m_alphaRef = ref/255.0f; } if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) ) { if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags) { float pointSize = (float)(bx::uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) ); GL_CHECK(glPointSize(pointSize) ); } if (BGFX_STATE_MSAA & changedFlags) { GL_CHECK(BGFX_STATE_MSAA & newFlags ? glEnable(GL_MULTISAMPLE) : glDisable(GL_MULTISAMPLE) ); } if (BGFX_STATE_LINEAA & changedFlags) { GL_CHECK(BGFX_STATE_LINEAA & newFlags ? glEnable(GL_LINE_SMOOTH) : glDisable(GL_LINE_SMOOTH) ); } if (m_conservativeRasterSupport && BGFX_STATE_CONSERVATIVE_RASTER & changedFlags) { GL_CHECK(BGFX_STATE_CONSERVATIVE_RASTER & newFlags ? glEnable(GL_CONSERVATIVE_RASTERIZATION_NV) : glDisable(GL_CONSERVATIVE_RASTERIZATION_NV) ); } } if ( (BGFX_STATE_WRITE_A|BGFX_STATE_WRITE_RGB) & changedFlags) { const GLboolean rr = !!(newFlags&BGFX_STATE_WRITE_R); const GLboolean gg = !!(newFlags&BGFX_STATE_WRITE_G); const GLboolean bb = !!(newFlags&BGFX_STATE_WRITE_B); const GLboolean aa = !!(newFlags&BGFX_STATE_WRITE_A); GL_CHECK(glColorMask(rr, gg, bb, aa) ); } if ( ( (0 | BGFX_STATE_BLEND_MASK | BGFX_STATE_BLEND_EQUATION_MASK | BGFX_STATE_BLEND_INDEPENDENT | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE ) & changedFlags) || blendFactor != draw.m_rgba) { if (m_atocSupport) { if (BGFX_STATE_BLEND_ALPHA_TO_COVERAGE & newFlags) { GL_CHECK(glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) ); } else { GL_CHECK(glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE) ); } } if ( ( (0 | BGFX_STATE_BLEND_MASK | BGFX_STATE_BLEND_EQUATION_MASK | BGFX_STATE_BLEND_INDEPENDENT) & newFlags) || blendFactor != draw.m_rgba) { const bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags); const bool independent = !!(BGFX_STATE_BLEND_INDEPENDENT & newFlags) && blendIndependentSupported ; const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT); const uint32_t srcRGB = (blend )&0xf; const uint32_t dstRGB = (blend>> 4)&0xf; const uint32_t srcA = (blend>> 8)&0xf; const uint32_t dstA = (blend>>12)&0xf; const uint32_t equ = uint32_t( (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT); const uint32_t equRGB = (equ )&0x7; const uint32_t equA = (equ>>3)&0x7; const uint32_t numRt = getNumRt(); if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || 1 >= numRt || !independent) { if (enabled) { GL_CHECK(glEnable(GL_BLEND) ); GL_CHECK(glBlendFuncSeparate(s_blendFactor[srcRGB].m_src , s_blendFactor[dstRGB].m_dst , s_blendFactor[srcA].m_src , s_blendFactor[dstA].m_dst ) ); GL_CHECK(glBlendEquationSeparate(s_blendEquation[equRGB], s_blendEquation[equA]) ); if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor) && blendFactor != draw.m_rgba) { const uint32_t rgba = draw.m_rgba; GLclampf rr = ( (rgba>>24) )/255.0f; GLclampf gg = ( (rgba>>16)&0xff)/255.0f; GLclampf bb = ( (rgba>> 8)&0xff)/255.0f; GLclampf aa = ( (rgba )&0xff)/255.0f; GL_CHECK(glBlendColor(rr, gg, bb, aa) ); } } else { GL_CHECK(glDisable(GL_BLEND) ); } } else { if (enabled) { GL_CHECK(glEnablei(GL_BLEND, 0) ); GL_CHECK(glBlendFuncSeparatei(0 , s_blendFactor[srcRGB].m_src , s_blendFactor[dstRGB].m_dst , s_blendFactor[srcA].m_src , s_blendFactor[dstA].m_dst ) ); GL_CHECK(glBlendEquationSeparatei(0 , s_blendEquation[equRGB] , s_blendEquation[equA] ) ); } else { GL_CHECK(glDisablei(GL_BLEND, 0) ); } for (uint32_t ii = 1, rgba = draw.m_rgba; ii < numRt; ++ii, rgba >>= 11) { if (0 != (rgba&0x7ff) ) { const uint32_t src = (rgba )&0xf; const uint32_t dst = (rgba>>4)&0xf; const uint32_t equation = (rgba>>8)&0x7; GL_CHECK(glEnablei(GL_BLEND, ii) ); GL_CHECK(glBlendFunci(ii, s_blendFactor[src].m_src, s_blendFactor[dst].m_dst) ); GL_CHECK(glBlendEquationi(ii, s_blendEquation[equation]) ); } else { GL_CHECK(glDisablei(GL_BLEND, ii) ); } } } } else { GL_CHECK(glDisable(GL_BLEND) ); } blendFactor = draw.m_rgba; } const uint64_t pt = newFlags&BGFX_STATE_PT_MASK; primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT); prim = s_primInfo[primIndex]; } bool programChanged = false; bool constantsChanged = draw.m_uniformBegin < draw.m_uniformEnd; bool bindAttribs = false; rendererUpdateUniforms(this, _render->m_uniformBuffer[draw.m_uniformIdx], draw.m_uniformBegin, draw.m_uniformEnd); if (key.m_program.idx != currentProgram.idx) { currentProgram = key.m_program; GLuint id = isValid(currentProgram) ? m_program[currentProgram.idx].m_id : 0; // Skip rendering if program index is valid, but program is invalid. currentProgram = 0 == id ? ProgramHandle{kInvalidHandle} : currentProgram; GL_CHECK(glUseProgram(id) ); programChanged = constantsChanged = bindAttribs = true; } if (isValid(currentProgram) ) { ProgramGL& program = m_program[currentProgram.idx]; if (constantsChanged && NULL != program.m_constantBuffer) { commit(*program.m_constantBuffer); } viewState.setPredefined<1>(this, view, program, _render, draw); { for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage) { const Binding& bind = renderBind.m_bind[stage]; Binding& current = currentBind.m_bind[stage]; if (current.m_idx != bind.m_idx || current.m_type != bind.m_type || current.m_samplerFlags != bind.m_samplerFlags || programChanged) { if (kInvalidHandle != bind.m_idx) { switch (bind.m_type) { case Binding::Texture: { TextureGL& texture = m_textures[bind.m_idx]; texture.commit(stage, bind.m_samplerFlags, _render->m_colorPalette); } break; case Binding::IndexBuffer: { const IndexBufferGL& buffer = m_indexBuffers[bind.m_idx]; GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, stage, buffer.m_id) ); } break; case Binding::VertexBuffer: { const VertexBufferGL& buffer = m_vertexBuffers[bind.m_idx]; GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, stage, buffer.m_id) ); } break; } } } current = bind; } } { bool diffStreamHandles = false; for (uint32_t idx = 0, streamMask = draw.m_streamMask ; 0 != streamMask ; streamMask >>= 1, idx += 1 ) { const uint32_t ntz = bx::uint32_cnttz(streamMask); streamMask >>= ntz; idx += ntz; if (currentState.m_stream[idx].m_handle.idx != draw.m_stream[idx].m_handle.idx) { diffStreamHandles = true; break; } } if (programChanged || currentState.m_streamMask != draw.m_streamMask || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx || currentState.m_instanceDataOffset != draw.m_instanceDataOffset || currentState.m_instanceDataStride != draw.m_instanceDataStride || diffStreamHandles) { currentState.m_streamMask = draw.m_streamMask; currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx; currentState.m_instanceDataOffset = draw.m_instanceDataOffset; currentState.m_instanceDataStride = draw.m_instanceDataStride; for (uint32_t idx = 0, streamMask = draw.m_streamMask ; 0 != streamMask ; streamMask >>= 1, idx += 1 ) { const uint32_t ntz = bx::uint32_cnttz(streamMask); streamMask >>= ntz; idx += ntz; currentState.m_stream[idx].m_handle = draw.m_stream[idx].m_handle; } bindAttribs = true; } if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx) { currentState.m_indexBuffer = draw.m_indexBuffer; uint16_t handle = draw.m_indexBuffer.idx; if (kInvalidHandle != handle) { IndexBufferGL& ib = m_indexBuffers[handle]; GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) ); } else { GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) ); } } if (0 != currentState.m_streamMask) { bool diffStartVertex = false; for (uint32_t idx = 0, streamMask = draw.m_streamMask ; 0 != streamMask ; streamMask >>= 1, idx += 1 ) { const uint32_t ntz = bx::uint32_cnttz(streamMask); streamMask >>= ntz; idx += ntz; if (currentState.m_stream[idx].m_startVertex != draw.m_stream[idx].m_startVertex) { diffStartVertex = true; break; } } if (bindAttribs || diffStartVertex) { if (isValid(boundProgram) ) { m_program[boundProgram.idx].unbindAttributes(); boundProgram = BGFX_INVALID_HANDLE; } boundProgram = currentProgram; program.bindAttributesBegin(); if (UINT8_MAX != draw.m_streamMask) { for (uint32_t idx = 0, streamMask = draw.m_streamMask ; 0 != streamMask ; streamMask >>= 1, idx += 1 ) { const uint32_t ntz = bx::uint32_cnttz(streamMask); streamMask >>= ntz; idx += ntz; currentState.m_stream[idx].m_startVertex = draw.m_stream[idx].m_startVertex; const VertexBufferGL& vb = m_vertexBuffers[draw.m_stream[idx].m_handle.idx]; const uint16_t decl = isValid(draw.m_stream[idx].m_layoutHandle) ? draw.m_stream[idx].m_layoutHandle.idx : vb.m_layoutHandle.idx; GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) ); program.bindAttributes(m_vertexLayouts[decl], draw.m_stream[idx].m_startVertex); } } program.bindAttributesEnd(); if (isValid(draw.m_instanceDataBuffer) ) { GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffers[draw.m_instanceDataBuffer.idx].m_id) ); program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset); } } } } if (0 != currentState.m_streamMask) { uint32_t numVertices = draw.m_numVertices; if (UINT32_MAX == numVertices) { for (uint32_t idx = 0, streamMask = draw.m_streamMask ; 0 != streamMask ; streamMask >>= 1, idx += 1 ) { const uint32_t ntz = bx::uint32_cnttz(streamMask); streamMask >>= ntz; idx += ntz; const VertexBufferGL& vb = m_vertexBuffers[draw.m_stream[idx].m_handle.idx]; uint16_t decl = !isValid(vb.m_layoutHandle) ? draw.m_stream[idx].m_layoutHandle.idx : vb.m_layoutHandle.idx; const VertexLayout& layout = m_vertexLayouts[decl]; numVertices = bx::uint32_min(numVertices, vb.m_size/layout.m_stride); } } uint32_t numIndices = 0; uint32_t numPrimsSubmitted = 0; uint32_t numInstances = 0; uint32_t numPrimsRendered = 0; uint32_t numDrawIndirect = 0; if (hasOcclusionQuery) { m_occlusionQuery.begin(_render, draw.m_occlusionQuery); } if (isValid(draw.m_indirectBuffer) ) { const VertexBufferGL& vb = m_vertexBuffers[draw.m_indirectBuffer.idx]; if (currentState.m_indirectBuffer.idx != draw.m_indirectBuffer.idx) { currentState.m_indirectBuffer = draw.m_indirectBuffer; GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, vb.m_id) ); } if (isValid(draw.m_indexBuffer) ) { const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx]; const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32); const GLenum indexFormat = hasIndex16 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT ; numDrawIndirect = UINT16_MAX == draw.m_numIndirect ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE : draw.m_numIndirect ; uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE; GL_CHECK(glMultiDrawElementsIndirect(prim.m_type, indexFormat , (void*)args , numDrawIndirect , BGFX_CONFIG_DRAW_INDIRECT_STRIDE ) ); } else { numDrawIndirect = UINT16_MAX == draw.m_numIndirect ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE : draw.m_numIndirect ; uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE; GL_CHECK(glMultiDrawArraysIndirect(prim.m_type , (void*)args , numDrawIndirect , BGFX_CONFIG_DRAW_INDIRECT_STRIDE ) ); } } else { if (isValid(currentState.m_indirectBuffer) ) { currentState.m_indirectBuffer.idx = kInvalidHandle; GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0) ); } if (isValid(draw.m_indexBuffer) ) { const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx]; const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32); const uint32_t indexSize = hasIndex16 ? 2 : 4; const GLenum indexFormat = hasIndex16 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT ; if (UINT32_MAX == draw.m_numIndices) { numIndices = ib.m_size/indexSize; numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub; numInstances = draw.m_numInstances; numPrimsRendered = numPrimsSubmitted*draw.m_numInstances; GL_CHECK(glDrawElementsInstanced(prim.m_type , numIndices , indexFormat , (void*)0 , draw.m_numInstances ) ); } else if (prim.m_min <= draw.m_numIndices) { numIndices = draw.m_numIndices; numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub; numInstances = draw.m_numInstances; numPrimsRendered = numPrimsSubmitted*draw.m_numInstances; GL_CHECK(glDrawElementsInstanced(prim.m_type , numIndices , indexFormat , (void*)(uintptr_t)(draw.m_startIndex*indexSize) , draw.m_numInstances ) ); } } else { numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub; numInstances = draw.m_numInstances; numPrimsRendered = numPrimsSubmitted*draw.m_numInstances; GL_CHECK(glDrawArraysInstanced(prim.m_type , 0 , numVertices , draw.m_numInstances ) ); } } if (hasOcclusionQuery) { m_occlusionQuery.end(); } if(isValid(draw.m_instanceDataBuffer)) { program.unbindInstanceData(); } statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted; statsNumPrimsRendered[primIndex] += numPrimsRendered; statsNumInstances[primIndex] += numInstances; statsNumIndices += numIndices; } } } if (isValid(boundProgram) ) { m_program[boundProgram.idx].unbindAttributes(); boundProgram = BGFX_INVALID_HANDLE; } if (wasCompute) { setViewType(view, "C"); BGFX_GL_PROFILER_END(); BGFX_GL_PROFILER_BEGIN(view, kColorCompute); } submitBlit(bs, BGFX_CONFIG_MAX_VIEWS); blitMsaaFbo(); if (m_vaoSupport) { GL_CHECK(glBindVertexArray(m_vao) ); } if (0 < _render->m_numRenderItems) { if (0 != (m_resolution.reset & BGFX_RESET_FLUSH_AFTER_RENDER) ) { GL_CHECK(glFlush() ); } captureElapsed = -bx::getHPCounter(); capture(); captureElapsed += bx::getHPCounter(); profiler.end(); } } BGFX_GL_PROFILER_END(); m_glctx.makeCurrent(NULL); int64_t timeEnd = bx::getHPCounter(); int64_t frameTime = timeEnd - timeBegin; static int64_t min = frameTime; static int64_t max = frameTime; min = min > frameTime ? frameTime : min; max = max < frameTime ? frameTime : max; static uint32_t maxGpuLatency = 0; static double maxGpuElapsed = 0.0f; double elapsedGpuMs = 0.0; if (UINT32_MAX != frameQueryIdx) { m_gpuTimer.end(frameQueryIdx); const TimerQueryGL::Result& result = m_gpuTimer.m_result[BGFX_CONFIG_MAX_VIEWS]; double toGpuMs = 1000.0 / 1e9; elapsedGpuMs = (result.m_end - result.m_begin) * toGpuMs; maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed; maxGpuLatency = bx::uint32_imax(maxGpuLatency, result.m_pending-1); } const int64_t timerFreq = bx::getHPFrequency(); Stats& perfStats = _render->m_perfStats; perfStats.cpuTimeBegin = timeBegin; perfStats.cpuTimeEnd = timeEnd; perfStats.cpuTimerFreq = timerFreq; const TimerQueryGL::Result& result = m_gpuTimer.m_result[BGFX_CONFIG_MAX_VIEWS]; perfStats.gpuTimeBegin = result.m_begin; perfStats.gpuTimeEnd = result.m_end; perfStats.gpuTimerFreq = 1000000000; perfStats.numDraw = statsKeyType[0]; perfStats.numCompute = statsKeyType[1]; perfStats.numBlit = _render->m_numBlitItems; perfStats.maxGpuLatency = maxGpuLatency; bx::memCopy(perfStats.numPrims, statsNumPrimsRendered, sizeof(perfStats.numPrims) ); perfStats.gpuMemoryMax = -INT64_MAX; perfStats.gpuMemoryUsed = -INT64_MAX; if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) ) { BGFX_GL_PROFILER_BEGIN_LITERAL("debugstats", kColorFrame); m_needPresent = true; TextVideoMem& tvm = m_textVideoMem; static int64_t next = timeEnd; if (timeEnd >= next) { next = timeEnd + timerFreq; double freq = double(timerFreq); double toMs = 1000.0/freq; tvm.clear(); uint16_t pos = 0; tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x8c : 0x8f , " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " " , getRendererName() ); tvm.printf(0, pos++, 0x8f, " Vendor: %s ", m_vendor); tvm.printf(0, pos++, 0x8f, " Renderer: %s ", m_renderer); tvm.printf(0, pos++, 0x8f, " Version: %s ", m_version); tvm.printf(0, pos++, 0x8f, " GLSL version: %s ", m_glslVersion); char processMemoryUsed[16]; bx::prettify(processMemoryUsed, BX_COUNTOF(processMemoryUsed), bx::getProcessMemoryUsed() ); tvm.printf(0, pos++, 0x8f, " Memory: %s (process) ", processMemoryUsed); pos = 10; tvm.printf(10, pos++, 0x8b, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS " , double(frameTime)*toMs , double(min)*toMs , double(max)*toMs , freq/frameTime ); const uint32_t msaa = (m_resolution.reset&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT; tvm.printf(10, pos++, 0x8b, " Reset flags: [%c] vsync, [%c] MSAAx%d, [%c] MaxAnisotropy " , !!(m_resolution.reset&BGFX_RESET_VSYNC) ? '\xfe' : ' ' , 0 != msaa ? '\xfe' : ' ' , 1<<msaa , !!(m_resolution.reset&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' ' ); double elapsedCpuMs = double(frameTime)*toMs; tvm.printf(10, pos++, 0x8b, " Submitted: %5d (draw %5d, compute %4d) / CPU %7.4f [ms] %c GPU %7.4f [ms] (latency %d) " , _render->m_numRenderItems , statsKeyType[0] , statsKeyType[1] , elapsedCpuMs , elapsedCpuMs > elapsedGpuMs ? '>' : '<' , maxGpuElapsed , maxGpuLatency ); maxGpuLatency = 0; maxGpuElapsed = 0.0; for (uint32_t ii = 0; ii < BX_COUNTOF(s_primInfo); ++ii) { tvm.printf(10, pos++, 0x8b, " %10s: %7d (#inst: %5d), submitted: %7d " , getName(Topology::Enum(ii) ) , statsNumPrimsRendered[ii] , statsNumInstances[ii] , statsNumPrimsSubmitted[ii] ); } if (NULL != m_renderdocdll) { tvm.printf(tvm.m_width-27, 0, 0x4f, " [F11 - RenderDoc capture] "); } tvm.printf(10, pos++, 0x8b, " Indices: %7d ", statsNumIndices); // tvm.printf(10, pos++, 0x8b, " Uniform size: %7d, Max: %7d ", _render->m_uniformEnd, _render->m_uniformMax); tvm.printf(10, pos++, 0x8b, " DVB size: %7d ", _render->m_vboffset); tvm.printf(10, pos++, 0x8b, " DIB size: %7d ", _render->m_iboffset); pos++; tvm.printf(10, pos++, 0x8b, " State cache: "); tvm.printf(10, pos++, 0x8b, " Sampler "); tvm.printf(10, pos++, 0x8b, " %6d " , m_samplerStateCache.getCount() ); #if BGFX_CONFIG_RENDERER_OPENGL if (s_extension[Extension::ATI_meminfo].m_supported) { GLint vboFree[4]; GL_CHECK(glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, vboFree) ); GLint texFree[4]; GL_CHECK(glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, texFree) ); GLint rbfFree[4]; GL_CHECK(glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, rbfFree) ); pos++; tvm.printf(10, pos++, 0x8c, " -------------| free| free b| aux| aux fb "); char tmp0[16]; char tmp1[16]; char tmp2[16]; char tmp3[16]; bx::prettify(tmp0, BX_COUNTOF(tmp0), vboFree[0]); bx::prettify(tmp1, BX_COUNTOF(tmp1), vboFree[1]); bx::prettify(tmp2, BX_COUNTOF(tmp2), vboFree[2]); bx::prettify(tmp3, BX_COUNTOF(tmp3), vboFree[3]); tvm.printf(10, pos++, 0x8b, " VBO: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3); bx::prettify(tmp0, BX_COUNTOF(tmp0), texFree[0]); bx::prettify(tmp1, BX_COUNTOF(tmp1), texFree[1]); bx::prettify(tmp2, BX_COUNTOF(tmp2), texFree[2]); bx::prettify(tmp3, BX_COUNTOF(tmp3), texFree[3]); tvm.printf(10, pos++, 0x8b, " Texture: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3); bx::prettify(tmp0, BX_COUNTOF(tmp0), rbfFree[0]); bx::prettify(tmp1, BX_COUNTOF(tmp1), rbfFree[1]); bx::prettify(tmp2, BX_COUNTOF(tmp2), rbfFree[2]); bx::prettify(tmp3, BX_COUNTOF(tmp3), rbfFree[3]); tvm.printf(10, pos++, 0x8b, " Render Buffer: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3); } else if (s_extension[Extension::NVX_gpu_memory_info].m_supported) { GLint dedicated; GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated) ); GLint totalAvail; GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &totalAvail) ); GLint currAvail; GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &currAvail) ); GLint evictedCount; GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &evictedCount) ); GLint evictedMemory; GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &evictedMemory) ); pos++; char tmp0[16]; char tmp1[16]; bx::prettify(tmp0, BX_COUNTOF(tmp0), dedicated); tvm.printf(10, pos++, 0x8b, " Dedicated: %10s ", tmp0); bx::prettify(tmp0, BX_COUNTOF(tmp0), currAvail); bx::prettify(tmp1, BX_COUNTOF(tmp1), totalAvail); tvm.printf(10, pos++, 0x8b, " Available: %10s / %10s ", tmp0, tmp1); bx::prettify(tmp0, BX_COUNTOF(tmp0), evictedCount); bx::prettify(tmp1, BX_COUNTOF(tmp1), evictedMemory); tvm.printf(10, pos++, 0x8b, " Eviction: %10s / %10s ", tmp0, tmp1); } #endif // BGFX_CONFIG_RENDERER_OPENGL pos++; double captureMs = double(captureElapsed)*toMs; tvm.printf(10, pos++, 0x8b, " Capture: %7.4f [ms] ", captureMs); uint8_t attr[2] = { 0x8c, 0x8a }; uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender; tvm.printf(10, pos++, attr[attrIndex&1], " Submit wait: %7.4f [ms] ", double(_render->m_waitSubmit)*toMs); tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %7.4f [ms] ", double(_render->m_waitRender)*toMs); min = frameTime; max = frameTime; } blit(this, _textVideoMemBlitter, tvm); BGFX_GL_PROFILER_END(); } else if (_render->m_debug & BGFX_DEBUG_TEXT) { BGFX_GL_PROFILER_BEGIN_LITERAL("debugtext", kColorFrame); blit(this, _textVideoMemBlitter, _render->m_textVideoMem); BGFX_GL_PROFILER_END(); } } } } // namespace bgfx #else namespace bgfx { namespace gl { RendererContextI* rendererCreate(const Init& _init) { BX_UNUSED(_init); return NULL; } void rendererDestroy() { } } /* namespace gl */ } // namespace bgfx #endif // (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)
; This is the entry point for the application processors. ; It is loaded at 0x8000 by HermitCore and filled with parameters. ; It does the switch from Real Mode -> Protected Mode -> Long Mode, ; sets up CR3 for this CPU, and then calls into entry.asm. ; ; In contrast to this self-contained entry point, entry.asm is linked ; to the rest of HermitCore and thus has access to all exported symbols ; (like the actual Rust entry point). CR0_PG equ (1 << 31) CR4_PAE equ (1 << 5) MSR_EFER equ 0xC0000080 EFER_LME equ (1 << 8) EFER_NXE equ (1 << 11) [BITS 16] SECTION .text GLOBAL _start ORG 0x8000 _start: jmp _rmstart ; PARAMETERS align 8 entry_point dq 0xDEADC0DE boot_info dq 0xBEEFBEEF pml4 dd 0xDEADBEEF pad dd 0; _rmstart: cli lgdt [gdtr] ; switch to protected mode by setting PE bit mov eax, cr0 or al, 0x1 mov cr0, eax ; far jump to the 32bit code jmp dword codesel : _pmstart [BITS 32] ALIGN 4 _pmstart: xor eax, eax mov ax, datasel mov ds, ax mov es, ax mov fs, ax mov gs, ax mov ss, ax jmp short stublet jmp $ ; GDT for the protected mode ALIGN 4 gdtr: ; descritor table dw gdt_end-gdt-1 ; limit dd gdt ; base address gdt: dd 0,0 ; null descriptor codesel equ $-gdt dw 0xFFFF ; segment size 0..15 dw 0x0000 ; segment address 0..15 db 0x00 ; segment address 16..23 db 0x9A ; access permissions und type db 0xCF ; additional information and segment size 16...19 db 0x00 ; segment address 24..31 datasel equ $-gdt dw 0xFFFF ; segment size 0..15 dw 0x0000 ; segment address 0..15 db 0x00 ; segment address 16..23 db 0x92 ; access permissions and type db 0xCF ; additional informationen and degment size 16...19 db 0x00 ; segment address 24..31 gdt_end: ALIGN 4 GDTR64: dw GDT64_end - GDT64 - 1 ; Limit. dq GDT64 ; Base. ; we need a new GDT to switch in the 64bit modus GDT64: ; Global Descriptor Table (64-bit). .Null: equ $ - GDT64 ; The null descriptor. dw 0 ; Limit (low). dw 0 ; Base (low). db 0 ; Base (middle) db 0 ; Access. db 0 ; Granularity. db 0 ; Base (high). .Code: equ $ - GDT64 ; The code descriptor. dw 0 ; Limit (low). dw 0 ; Base (low). db 0 ; Base (middle) db 10011010b ; Access. db 00100000b ; Granularity. db 0 ; Base (high). .Data: equ $ - GDT64 ; The data descriptor. dw 0 ; Limit (low). dw 0 ; Base (low). db 0 ; Base (middle) db 10010010b ; Access. db 00000000b ; Granularity. db 0 ; Base (high). GDT64_end: ALIGN 4 stublet: ; Enable PAE mode. mov eax, cr4 or eax, CR4_PAE mov cr4, eax ; Set the address to PML4 in CR3. mov eax, dword [pml4] mov cr3, eax ; Enable x86-64 Compatibility Mode by setting EFER_LME. ; Also enable early access to EXECUTE_DISABLE-protected memory through EFER_NXE. mov ecx, MSR_EFER rdmsr or eax, EFER_LME | EFER_NXE wrmsr ; Enable Paging. mov eax, cr0 or eax, CR0_PG mov cr0, eax ; Load the 64-bit global descriptor table. lgdt [GDTR64] mov ax, GDT64.Data mov ss, ax mov ds, ax mov es, ax ; Set the code segment and enter 64-bit long mode. jmp GDT64.Code:start64 [BITS 64] ALIGN 8 start64: ; forward address to boot info mov rdi, qword [boot_info] ; Jump to entry.asm jmp qword [entry_point]
.( CA = $dc + TILE_ALPHANUM_A CB = $dc + TILE_ALPHANUM_B CC = $dc + TILE_ALPHANUM_C CD = $dc + TILE_ALPHANUM_D CE = $dc + TILE_ALPHANUM_E CF = $dc + TILE_ALPHANUM_F CG = $dc + TILE_ALPHANUM_G CH = $dc + TILE_ALPHANUM_H CI = $dc + TILE_ALPHANUM_I CJ = $dc + TILE_ALPHANUM_J CK = $dc + TILE_ALPHANUM_K CL = $dc + TILE_ALPHANUM_L CM = $dc + TILE_ALPHANUM_M CN = $dc + TILE_ALPHANUM_N CO = $dc + TILE_ALPHANUM_O CP = $dc + TILE_ALPHANUM_P CQ = $dc + TILE_ALPHANUM_Q CR = $dc + TILE_ALPHANUM_R CS = $dc + TILE_ALPHANUM_S CT = $dc + TILE_ALPHANUM_T CU = $dc + TILE_ALPHANUM_U CV = $dc + TILE_ALPHANUM_V CW = $dc + TILE_ALPHANUM_W CX = $dc + TILE_ALPHANUM_X CY = $dc + TILE_ALPHANUM_Y CZ = $dc + TILE_ALPHANUM_Z T0 = TILE_MENU_ONLINE_MODE_DIALOGS_00 T1 = TILE_MENU_ONLINE_MODE_DIALOGS_01 T2 = TILE_MENU_ONLINE_MODE_DIALOGS_02 T3 = TILE_MENU_ONLINE_MODE_DIALOGS_03 T4 = TILE_MENU_ONLINE_MODE_DIALOGS_04 T5 = TILE_MENU_ONLINE_MODE_DIALOGS_05 T6 = TILE_MENU_ONLINE_MODE_DIALOGS_06 T7 = TILE_MENU_ONLINE_MODE_DIALOGS_07 T8 = TILE_MENU_ONLINE_MODE_DIALOGS_08 T9 = TILE_MENU_ONLINE_MODE_DIALOGS_09 TA = TILE_MENU_ONLINE_MODE_DIALOGS_0A TB = TILE_MENU_ONLINE_MODE_DIALOGS_0B TC = TILE_MENU_ONLINE_MODE_DIALOGS_0C TD = TILE_MENU_ONLINE_MODE_DIALOGS_0D TE = TILE_MENU_ONLINE_MODE_DIALOGS_0E &menu_online_mode_palette: ; Background ; 0-sky/inactive_box, 1-stars/active_box, 2-earth, 3-title .byt $0f,$02,$11,$21, $0f,$08,$28,$20, $0f,$29,$02,$21, $0f,$28,$20,$21 ; Sprites ; 0-earth, 1-cursor/ship, 2-unused, 3-unused .byt $0f,$29,$02,$0f, $0f,$28,$0f,$20, $0f,$00,$00,$00, $0f,$00,$00,$00 &menu_online_mode_palette_transition: ; Background ; 0-sky/inactive_box, 1-stars/active_box, 2-earth, 3-title .byt $21,$02,$11,$21, $21,$08,$28,$20, $21,$29,$02,$21, $21,$28,$20,$21 ; Sprites ; 0-earth, 1-cursor/ship, 2-unused, 3-unused .byt $21,$29,$02,$0f, $21,$28,$0f,$20, $21,$00,$00,$00, $21,$00,$00,$00 &menu_online_mode_nametable: .byt $00,$6b .byt .byt .byt $01, $02, $03, $04, $05, ZIPZ,$06, $03, $04, $07, $08, $00,$15 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $09, $0a, $0b, $0c, $0d, $0e, $0f, $0b, $0c, $10, $11, $00,$0c .byt $12, $13, $14, $15, $00,$02, $12, $13, ZIPZ,$16, $00,$02, $17, $15, $00,$02, $12, $13, $14, $15, $00,$02, $18, $13, $00,$03, $19, $17, $15 .byt $18, $1a, $1b, $1c, $1c, $1d, $1e, $1f, $20, $21, $22, $23, $24, $25, $26, $26, $27, $1a, $1b, $1c, $1c, $1d, $1e, $1f, $20, $21, $22, $23, $24, $25, $28, $26 .byt $26, $26, $29, $2a, $2b, CC, CA, CS, CU, CA, CL, $2b, $2b, $2c, $26, $26, $26, $26, $29, $2a, $2b, CR, CA, CN, CK, CE, CD, $2b, $2b, $2c, $26, $26 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $26, $26, $2d, $2e, $2b, $2b, $2b, $2f, $2b, $2b, $2b, $30, $2b, $31, $26, $26, $26, $26, $2d, $2e, $2b, $2b, $32, $33, $34, $35, $2b, $30, $2b, $31, $26, $26 .byt $26, $26, $36, $2b, $2b, $2b, $37, $38, $39, $3a, $2b, $3b, $3c, $3d, $26, $26, $26, $26, $36, $2b, $2b, $2b, $3e, $3f, $40, $41, $2b, $3b, $3c, $3d, $26, $26 .byt $26, $26, $42, $2b, $43, $2b, $44, $45, $46, $47, $2b, $2b, $48, $49, $4a, $4b, $4c, $4d, $42, $2b, $43, $2b, $4e, $4f, $50, $51, $2b, $2b, $48, $49, $26, $26 .byt $26, $26, $52, $53, $54, $55, $56, $57, $58, $59, $2b, $2b, $2b, $5a, $5b, $5c, $5d, $5e, $52, $53, $54, $55, $5f, $60, $61, $2b, $2b, $2b, $2b, $5a, $26, $26 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $26, $26, $62, $2b, $2b, $2b, $2b, $63, $64, $2b, $2b, $65, $66, $67, $68, $69, $6a, $6b, $62, $2b, $2b, $2b, $2b, $63, $64, $2b, $2b, $65, $66, $67, $26, $26 .byt $26, $26, $6c, $6d, $6e, $6f, $70, $71, $72, $73, $74, $75, $76, $77, $2b, $2b, $78, $79, $6c, $6d, $6e, $6f, $70, $71, $72, $73, $74, $75, $76, $77, $26, $26 .byt $26, $26, $26, $26, $26, $26, $7a, $26, $26, $26, $7b, $7c, $7d, $2b, $2b, $7e, $7f, $80, $80, $80, $81, $82, $26, $26, $26, $26, $26, $26, $26, $26, $26, $26 .byt $26, $26, $26, $26, $26, $26, $26, $26, $26, $26, $83, $84, $2b, $2b, $2b, $85, $80, $80, $80, $80, $86, $87, $26, $26, $26, $88, $26, $26, $26, $26, $26, $26 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $26, $26, $26, $88, $26, $26, $26, $26, $26, $26, $89, $8a, $8b, $8c, $2b, $3b, $8d, $8e, $8f, $80, $90, $91, $26, $26, $26, $26, $26, $26, $26, $92, $26, $26 .byt $26, $26, $26, $26, $26, $26, $26, $92, $26, $26, $93, $94, $80, $95, $96, $97, $2b, $2b, $98, $80, $99, $9a, $26, $26, $26, $26, $26, $26, $26, $26, $26, $26 .byt $26, $26, $1b, $1c, $1c, $1d, $1e, $1f, $20, $21, $22, $9b, $9c, $25, $9d, $9e, $2b, $2b, $1b, $1c, $1c, $1d, $1e, $1f, $20, $21, $22, $23, $24, $25, $26, $26 .byt $26, $26, $29, $2a, $2b, CP, CR, CI, CV, CA, CT, CE, $2b, $9f, $a0, $2b, $2b, $2b, $29, $2a, CS, CE, CT, CT, CI, CN, CG, CS, $2b, $2c, $26, $26 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $26, $26, $2d, $2e, $2b, $2b, $2b, $a1, $a2, $2b, $2b, $30, $2b, $31, $a3, $2b, $2b, $a4, $a5, $2e, $2b, $2b, $a6, $a7, $a8, $2b, $2b, $30, $2b, $31, $26, $26 .byt $26, $26, $36, $2b, $2b, $2b, $2b, $a9, $aa, $2b, $2b, $3b, $3c, $3d, $ab, $ac, $ad, $ae, $af, $2b, $2b, $b0, $b1, $b2, $b3, $a2, $2b, $3b, $3c, $3d, $26, $26 .byt $26, $26, $42, $2b, $43, $2b, $2b, $b4, $b5, $2b, $2b, $2b, $48, $49, $26, $26, $26, $26, $42, $2b, $43, $2b, $b6, $b7, $b8, $b9, $ba, $2b, $48, $49, $26, $26 .byt $26, $26, $52, $53, $54, $55, $bb, $bc, $bc, $bd, $2b, $2b, $2b, $5a, $26, $26, $26, $26, $52, $53, $54, $55, $56, $be, $bf, $c0, $c1, $2b, $2b, $5a, $26, $26 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $26, $26, $62, $2b, $2b, $2b, $2b, $63, $64, $2b, $2b, $65, $66, $67, $26, $26, $26, $26, $62, $2b, $2b, $2b, $2b, $63, $64, $2b, $2b, $65, $66, $67, $26, $26 .byt $26, $26, $6c, $6d, $6e, $6f, $70, $71, $72, $73, $74, $75, $76, $77, $26, $26, $26, $26, $6c, $6d, $6e, $6f, $70, $71, $72, $73, $74, $75, $76, $77, $26, $26 .byt $26, $26, $c2, $c3, $c4, $c5, $26, $26, $c2, $c3, $26, $26, $26, $26, $c4, $c5, $26, $26, $c2, $c3, $c4, $c5, $26, $26, $c6, $c3, $26, $26, $26, $26, $c4, $c5 .byt $c7, $c8, $00,$04, $c9, $c8, $00,$02, $c9, $c7, $c9, $c8, $00,$02, $c9, $c8, $00,$04, $c9, $c8, $00,$02, $c9, $c4, $c9, $c8, $00,$44 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt .byt .byt menu_online_mode_nametable_attributes: .byt $cc, $ff, $ff, $33, $00,$02 .byt $40, $50, $5c, $1f, $0f, $03, $00,$02 .byt $44, $55, $55, $91, $20, $00,$03 .byt $04, $55, $85, $a9, $a2, $20, $10, $00,$01 .byt $04, $04, $08, $8a, $2a, $02, $00,$01, $01, $00,$03 .byt $08, $02, .byt $00,$13 menu_online_mode_nametable_end: .byt ZIPNT_END &menu_online_mode_login_window: .byt 20, 10 ; width, height (in tiles) .byt T0, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T2 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, CU, CS, CE, CR, T4, CN, CA, CM, CE, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, CP, CA, CS, CS, CW, CO, CR, CD, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, T7, T8, T9, TA, T4, CO, CK, T4, T4, T4, TB, T4, CB, CA, CC, CK, T4, T5 .byt TC, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TE &menu_online_mode_game_password_window: .byt 20, 10 ; width, height (in tiles) .byt T0, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T2 .byt T3, T4, CS, CH, CA, CR, CE, T4, CP, CA, CS, CS, CW, CO, CR, CD, T4, T4, T4, T5 .byt T3, T4, CW, CI, CT, CH, T4, CY, CO, CU, CR, T4, CF, CR, CI, CE, CN, CD, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, CG, CA, CM, CE, T4, CP, CA, CS, CS, CW, CO, CR, CD, T4, T4, T4, T4, T5 .byt T3, T4, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T6, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, T7, T8, T9, TA, T4, CO, CK, T4, T4, T4, TB, T4, CB, CA, CC, CK, T4, T5 .byt TC, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TE &menu_online_mode_setting_select_window: .byt 20, 10 ; width, height (in tiles) .byt T0, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T2 .byt T3, T4, CN, CE, CT, CW, CO, CR, CK, T4, CS, CE, CT, CT, CI, CN, CG, CS, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, CC, CR, CE, CA, CT, CE, T4, CA, CC, CC, CO, CU, CN, CT, T4, T4, T4, T5 .byt T3, T4, CW, CI, CF, CI, T4, CS, CE, CT, CT, CI, CN, CG, T4, T4, T4, T4, T4, T5 .byt T3, T4, CG, CA, CM, CE, T4, CU, CP, CD, CA, CT, CE, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, T7, T8, T9, TA, T4, CO, CK, T4, T4, T4, TB, T4, CB, CA, CC, CK, T4, T5 .byt TC, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TE &menu_online_mode_deny_update_game_window: .byt 20, 10 ; width, height (in tiles) .byt T0, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T2 .byt T3, T4, CN, CO, CT, T4, CO, CN, T4, CE, CM, CU, CL, CA, CT, CO, CR, T4, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, CP, CL, CE, CA, CS, CE, T4, CD, CO, CW, CN, CL, CO, CA, CD, T4, T4, T5 .byt T3, T4, CT, CH, CE, T4, CL, CA, CT, CE, CS, CT, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, CV, CE, CR, CS, CI, CO, CN, T4, CM, CA, CN, CU, CA, CL, CL, CY, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt TC, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TE &menu_online_mode_deny_wifi_settings_window: .byt 20, 10 ; width, height (in tiles) .byt T0, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T1, T2 .byt T3, T4, CN, CO, CT, T4, CO, CN, T4, CE, CM, CU, CL, CA, CT, CO, CR, T4, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, CT, CH, CE, T4, CE, CM, CU, CL, CA, CT, CO, CR, T4, CU, CS, CE, CS, T5 .byt T3, T4, CY, CO, CU, CR, T4, CI, CN, CT, CE, CR, CN, CE, CT, T4, T4, T4, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, CN, CO, T4, CS, CP, CE, CC, CI, CF, CI, CC, T4, T4, T4, T4, T4, T4, T5 .byt T3, T4, CS, CE, CT, CT, CI, CN, CG, T4, CR, CE, CQ, CU, CI, CR, CE, CD, T4, T5 .byt T3, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T4, T5 .byt TC, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TE .)
mov r0, pointers mov r2, 4 loop: mov r1, [r0] mov r1, [r1] add r3, r1 add r0, 1 loop r2, loop sub r3, 1 # 10+20+40+30-1=99 mov [out], r3 halt .data out: data 0 pointers: data p1, p2, p3, p4 p1: data 10 p2: data 20 p4: data 40 p3: data 30
// Copyright (c) 2006-7 John Maddock // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_MATH_TOOLS_CONFIG_HPP #define BOOST_MATH_TOOLS_CONFIG_HPP #ifdef _MSC_VER #pragma once #endif #include <boost/config.hpp> #include <boost/predef.h> #include <boost/cstdint.hpp> // for boost::uintmax_t #include <boost/detail/workaround.hpp> #include <boost/type_traits/is_integral.hpp> #include <algorithm> // for min and max #include <boost/config/no_tr1/cmath.hpp> #include <climits> #include <cfloat> #if (defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)) # include <math.h> #endif #ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS # include <limits> #endif #include <boost/math/tools/user.hpp> #if (defined(__CYGWIN__) || defined(__FreeBSD__) || defined(__NetBSD__) \ || (defined(__hppa) && !defined(__OpenBSD__)) || (defined(__NO_LONG_DOUBLE_MATH) && (DBL_MANT_DIG != LDBL_MANT_DIG))) \ && !defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS) # define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #endif #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) // // Borland post 5.8.2 uses Dinkumware's std C lib which // doesn't have true long double precision. Earlier // versions are problematic too: // # define BOOST_MATH_NO_REAL_CONCEPT_TESTS # define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS # define BOOST_MATH_CONTROL_FP _control87(MCW_EM,MCW_EM) # include <float.h> #endif #ifdef __IBMCPP__ // // For reasons I don't unserstand, the tests with IMB's compiler all // pass at long double precision, but fail with real_concept, those tests // are disabled for now. (JM 2012). # define BOOST_MATH_NO_REAL_CONCEPT_TESTS #endif #ifdef sun // Any use of __float128 in program startup code causes a segfault (tested JM 2015, Solaris 11). # define BOOST_MATH_DISABLE_FLOAT128 #endif #ifdef __HAIKU__ // // Not sure what's up with the math detection on Haiku, but linking fails with // float128 code enabled, and we don't have an implementation of __expl, so // disabling long double functions for now as well. # define BOOST_MATH_DISABLE_FLOAT128 # define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #endif #if (defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)) && ((LDBL_MANT_DIG == 106) || (__LDBL_MANT_DIG__ == 106)) && !defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS) // // Darwin's rather strange "double double" is rather hard to // support, it should be possible given enough effort though... // # define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #endif #if defined(unix) && defined(__INTEL_COMPILER) && (__INTEL_COMPILER <= 1000) && !defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS) // // Intel compiler prior to version 10 has sporadic problems // calling the long double overloads of the std lib math functions: // calling ::powl is OK, but std::pow(long double, long double) // may segfault depending upon the value of the arguments passed // and the specific Linux distribution. // // We'll be conservative and disable long double support for this compiler. // // Comment out this #define and try building the tests to determine whether // your Intel compiler version has this issue or not. // # define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #endif #if defined(unix) && defined(__INTEL_COMPILER) // // Intel compiler has sporadic issues compiling std::fpclassify depending on // the exact OS version used. Use our own code for this as we know it works // well on Intel processors: // #define BOOST_MATH_DISABLE_STD_FPCLASSIFY #endif #if defined(BOOST_MSVC) && !defined(_WIN32_WCE) // Better safe than sorry, our tests don't support hardware exceptions: # define BOOST_MATH_CONTROL_FP _control87(MCW_EM,MCW_EM) #endif #ifdef __IBMCPP__ # define BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS #endif #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)) # define BOOST_MATH_USE_C99 #endif #if (defined(__hpux) && !defined(__hppa)) # define BOOST_MATH_USE_C99 #endif #if defined(__GNUC__) && defined(_GLIBCXX_USE_C99) # define BOOST_MATH_USE_C99 #endif #if defined(_LIBCPP_VERSION) && !defined(_MSC_VER) # define BOOST_MATH_USE_C99 #endif #if defined(__CYGWIN__) || defined(__HP_aCC) || defined(BOOST_INTEL) \ || defined(BOOST_NO_NATIVE_LONG_DOUBLE_FP_CLASSIFY) \ || (defined(__GNUC__) && !defined(BOOST_MATH_USE_C99))\ || defined(BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS) # define BOOST_MATH_NO_NATIVE_LONG_DOUBLE_FP_CLASSIFY #endif #if BOOST_WORKAROUND(__SUNPRO_CC, <= 0x590) # include "boost/type.hpp" # include "boost/non_type.hpp" # define BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(t) boost::type<t>* = 0 # define BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(t) boost::type<t>* # define BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE(t, v) boost::non_type<t, v>* = 0 # define BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) boost::non_type<t, v>* # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(t) \ , BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(t) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE_SPEC(t) \ , BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(t) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v) \ , BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE(t, v) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) \ , BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) #else // no workaround needed: expand to nothing # define BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(t) # define BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(t) # define BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE(t, v) # define BOOST_MATH_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(t) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE_SPEC(t) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_NON_TYPE(t, v) # define BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_NON_TYPE_SPEC(t, v) #endif // __SUNPRO_CC #if (defined(__SUNPRO_CC) || defined(__hppa) || defined(__GNUC__)) && !defined(BOOST_MATH_SMALL_CONSTANT) // Sun's compiler emits a hard error if a constant underflows, // as does aCC on PA-RISC, while gcc issues a large number of warnings: # define BOOST_MATH_SMALL_CONSTANT(x) 0.0 #else # define BOOST_MATH_SMALL_CONSTANT(x) x #endif #if BOOST_WORKAROUND(BOOST_MSVC, < 1400) // // Define if constants too large for a float cause "bad" // values to be stored in the data, rather than infinity // or a suitably large value. // # define BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS #endif // // Tune performance options for specific compilers: // #ifdef BOOST_MSVC # define BOOST_MATH_POLY_METHOD 2 # define BOOST_MATH_RATIONAL_METHOD 1 #elif defined(BOOST_INTEL) # define BOOST_MATH_POLY_METHOD 2 # define BOOST_MATH_RATIONAL_METHOD 1 #elif defined(__GNUC__) #if __GNUC__ < 4 # define BOOST_MATH_POLY_METHOD 3 # define BOOST_MATH_RATIONAL_METHOD 3 # define BOOST_MATH_INT_TABLE_TYPE(RT, IT) RT # define BOOST_MATH_INT_VALUE_SUFFIX(RV, SUF) RV##.0L #else # define BOOST_MATH_POLY_METHOD 3 # define BOOST_MATH_RATIONAL_METHOD 1 #endif #endif #if defined(BOOST_NO_LONG_LONG) && !defined(BOOST_MATH_INT_TABLE_TYPE) # define BOOST_MATH_INT_TABLE_TYPE(RT, IT) RT # define BOOST_MATH_INT_VALUE_SUFFIX(RV, SUF) RV##.0L #endif // // constexpr support, early GCC implementations can't cope so disable // constexpr for them: // #if !defined(__clang) && defined(__GNUC__) #if (__GNUC__ * 100 + __GNUC_MINOR__) < 490 # define BOOST_MATH_DISABLE_CONSTEXPR #endif #endif #ifdef BOOST_MATH_DISABLE_CONSTEXPR # define BOOST_MATH_CONSTEXPR #else # define BOOST_MATH_CONSTEXPR BOOST_CONSTEXPR #endif // // noexcept support: // #ifndef BOOST_NO_CXX11_NOEXCEPT #ifndef BOOST_NO_CXX11_HDR_TYPE_TRAITS #include <type_traits> # define BOOST_MATH_NOEXCEPT(T) noexcept(std::is_floating_point<T>::value) # define BOOST_MATH_IS_FLOAT(T) (std::is_floating_point<T>::value) #else #include <boost/type_traits/is_floating_point.hpp> # define BOOST_MATH_NOEXCEPT(T) noexcept(boost::is_floating_point<T>::value) # define BOOST_MATH_IS_FLOAT(T) (boost::is_floating_point<T>::value) #endif #else # define BOOST_MATH_NOEXCEPT(T) # define BOOST_MATH_IS_FLOAT(T) false #endif // // The maximum order of polynomial that will be evaluated // via an unrolled specialisation: // #ifndef BOOST_MATH_MAX_POLY_ORDER # define BOOST_MATH_MAX_POLY_ORDER 20 #endif // // Set the method used to evaluate polynomials and rationals: // #ifndef BOOST_MATH_POLY_METHOD # define BOOST_MATH_POLY_METHOD 2 #endif #ifndef BOOST_MATH_RATIONAL_METHOD # define BOOST_MATH_RATIONAL_METHOD 1 #endif // // decide whether to store constants as integers or reals: // #ifndef BOOST_MATH_INT_TABLE_TYPE # define BOOST_MATH_INT_TABLE_TYPE(RT, IT) IT #endif #ifndef BOOST_MATH_INT_VALUE_SUFFIX # define BOOST_MATH_INT_VALUE_SUFFIX(RV, SUF) RV##SUF #endif // // Test whether to support __float128, if we don't have quadmath.h then this can't currently work: // #ifndef BOOST_MATH_USE_FLOAT128 #ifdef __has_include #if ! __has_include("quadmath.h") #define BOOST_MATH_DISABLE_FLOAT128 #endif #elif !defined(BOOST_ARCH_X86) #define BOOST_MATH_DISABLE_FLOAT128 #endif #endif // // And then the actual configuration: // #if defined(_GLIBCXX_USE_FLOAT128) && defined(BOOST_GCC) && !defined(__STRICT_ANSI__) \ && !defined(BOOST_MATH_DISABLE_FLOAT128) || defined(BOOST_MATH_USE_FLOAT128) // // Only enable this when the compiler really is GCC as clang and probably // intel too don't support __float128 yet :-( // #ifndef BOOST_MATH_USE_FLOAT128 # define BOOST_MATH_USE_FLOAT128 #endif # if defined(BOOST_INTEL) && defined(BOOST_INTEL_CXX_VERSION) && (BOOST_INTEL_CXX_VERSION >= 1310) && defined(__GNUC__) # if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) # define BOOST_MATH_FLOAT128_TYPE __float128 # endif # elif defined(__GNUC__) # define BOOST_MATH_FLOAT128_TYPE __float128 # endif # ifndef BOOST_MATH_FLOAT128_TYPE # define BOOST_MATH_FLOAT128_TYPE _Quad # endif #endif // // Check for WinCE with no iostream support: // #if defined(_WIN32_WCE) && !defined(__SGI_STL_PORT) # define BOOST_MATH_NO_LEXICAL_CAST #endif // // Helper macro for controlling the FP behaviour: // #ifndef BOOST_MATH_CONTROL_FP # define BOOST_MATH_CONTROL_FP #endif // // Helper macro for using statements: // #define BOOST_MATH_STD_USING_CORE \ using std::abs;\ using std::acos;\ using std::cos;\ using std::fmod;\ using std::modf;\ using std::tan;\ using std::asin;\ using std::cosh;\ using std::frexp;\ using std::pow;\ using std::tanh;\ using std::atan;\ using std::exp;\ using std::ldexp;\ using std::sin;\ using std::atan2;\ using std::fabs;\ using std::log;\ using std::sinh;\ using std::ceil;\ using std::floor;\ using std::log10;\ using std::sqrt; #define BOOST_MATH_STD_USING BOOST_MATH_STD_USING_CORE namespace boost{ namespace math{ namespace tools { template <class T> inline T max BOOST_PREVENT_MACRO_SUBSTITUTION(T a, T b, T c) BOOST_MATH_NOEXCEPT(T) { return (std::max)((std::max)(a, b), c); } template <class T> inline T max BOOST_PREVENT_MACRO_SUBSTITUTION(T a, T b, T c, T d) BOOST_MATH_NOEXCEPT(T) { return (std::max)((std::max)(a, b), (std::max)(c, d)); } } // namespace tools template <class T> void suppress_unused_variable_warning(const T&) BOOST_MATH_NOEXCEPT(T) { } namespace detail{ template <class T> struct is_integer_for_rounding { static const bool value = boost::is_integral<T>::value #ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS || (std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer) #endif ; }; } }} // namespace boost namespace math #ifdef __GLIBC_PREREQ # if __GLIBC_PREREQ(2,14) # define BOOST_MATH_HAVE_FIXED_GLIBC # endif #endif #if ((defined(__linux__) && !defined(__UCLIBC__) && !defined(BOOST_MATH_HAVE_FIXED_GLIBC)) || defined(__QNX__) || defined(__IBMCPP__)) && !defined(BOOST_NO_FENV_H) // // This code was introduced in response to this glibc bug: http://sourceware.org/bugzilla/show_bug.cgi?id=2445 // Basically powl and expl can return garbage when the result is small and certain exception flags are set // on entrance to these functions. This appears to have been fixed in Glibc 2.14 (May 2011). // Much more information in this message thread: https://groups.google.com/forum/#!topic/boost-list/ZT99wtIFlb4 // #include <boost/detail/fenv.hpp> # ifdef FE_ALL_EXCEPT namespace boost{ namespace math{ namespace detail { struct fpu_guard { fpu_guard() { fegetexceptflag(&m_flags, FE_ALL_EXCEPT); feclearexcept(FE_ALL_EXCEPT); } ~fpu_guard() { fesetexceptflag(&m_flags, FE_ALL_EXCEPT); } private: fexcept_t m_flags; }; } // namespace detail }} // namespaces # define BOOST_FPU_EXCEPTION_GUARD boost::math::detail::fpu_guard local_guard_object; # define BOOST_MATH_INSTRUMENT_FPU do{ fexcept_t cpu_flags; fegetexceptflag(&cpu_flags, FE_ALL_EXCEPT); BOOST_MATH_INSTRUMENT_VARIABLE(cpu_flags); } while(0); # else # define BOOST_FPU_EXCEPTION_GUARD # define BOOST_MATH_INSTRUMENT_FPU # endif #else // All other platforms. # define BOOST_FPU_EXCEPTION_GUARD # define BOOST_MATH_INSTRUMENT_FPU #endif #ifdef BOOST_MATH_INSTRUMENT # include <iostream> # include <iomanip> # include <typeinfo> # define BOOST_MATH_INSTRUMENT_CODE(x) \ std::cout << std::setprecision(35) << __FILE__ << ":" << __LINE__ << " " << x << std::endl; # define BOOST_MATH_INSTRUMENT_VARIABLE(name) BOOST_MATH_INSTRUMENT_CODE(BOOST_STRINGIZE(name) << " = " << name) #else # define BOOST_MATH_INSTRUMENT_CODE(x) # define BOOST_MATH_INSTRUMENT_VARIABLE(name) #endif #endif // BOOST_MATH_TOOLS_CONFIG_HPP
10 ORG 100H 20 JP MAIN 30INKEY EQU 089BEH 35PUTCHR EQU 08440H 40INITSR EQU 0871AH 50OPENSR EQU 0BCE8H 60CLOSSR EQU 0BCEBH 70LRDSR EQU 0BD15H 80WAITK EQU 0BFCDH 90WSTSR EQU 0BFB2H 100MAIN: CALL INITSR 110 CALL OPENSR 115 CALL CLS 120 LD IX, L2 130 LD B, 4 140 LD HL, L1 150LOOP: LD A, (IX) 160 CALL BYTE 170 INC IX 250 DJNZ LOOP 260 LD HL, L0 270 CALL WSTSR 280 LD DE, 00100H 290 LD HL, L0 300 LD B, 37 310 CALL DSPSTR 320LOOP0: CALL INKEY 330 CP 0 350 JP Z, LOOP0 400 CALL CLOSSR 410 RET 500CLS: LD B, 6 502 LD DE, 0 504CLS1: PUSH BC 506 LD B, 24 508CLS2: LD A, 32 510 PUSH BC 512 PUSH DE 514 PUSH HL 516 CALL PUTCHR 518 POP HL 520 POP DE 522 POP BC 510 INC E 512 DJNZ CLS2 514 INC D 516 LD E, 0 518 POP BC 520 DJNZ CLS1 522 RET 600DSPSTR: LD A, (HL) 610 INC HL 620 PUSH BC 630 PUSH DE 640 PUSH HL 650 CALL PUTCHR 660 POP HL 670 POP DE 680 POP BC 690 INC E 700 LD A, E 710 SUB 24 720 JP M, SKIP0 730 INC D 740 LD E, 0 750SKIP0: DJNZ DSPSTR 760 RET 800BYTE: PUSH AF 810 AND 0F0H 811 RRCA 812 RRCA 813 RRCA 814 RRCA 815 CALL NIBBLE 816 INC HL 817 POP AF 818 AND 15 819 CALL NIBBLE 820 INC HL 821 RET 830NIBBLE: SUB 10 831 JP M, ZERO9 832 ADD A, 7 833ZERO9: ADD A, 58 834 LD (HL), A 835 RET 1000L0: DB 'Converting HEX to ASCII: 0x' 1001L1: DB 0,0,0,0,0,0,0,0 1002 DB 13,10,0 1010L2: DB 0DEH, 0CAH, 0FBH, 0ADH 
; A065995: a(n) = prime(prime(n) + n). ; Submitted by Jon Maiga ; 5,11,19,31,53,67,89,103,131,167,181,227,251,269,293,347,383,401,443,467,491,547,577,617,673,709,733,761,787,823,929,967,1013,1031,1097,1117,1181,1229,1277,1303,1373,1409,1481,1489,1531,1553,1627,1741,1783,1801,1861,1901,1931,2011,2069,2113,2161,2207,2267,2293,2311,2389,2531,2557,2593,2647,2729,2789,2861,2897,2939,3001,3079,3163,3209,3253,3313,3371,3413,3499,3571,3593,3677,3701,3767,3803,3863,3929,3989,4007,4049,4153,4231,4261,4349,4397,4457,4567,4597,4759 mov $2,$0 seq $0,40 ; The prime numbers. add $0,$2 seq $0,40 ; The prime numbers.
; ; Copyright (c) 2016, Alliance for Open Media. All rights reserved ; ; This source code is subject to the terms of the BSD 2 Clause License and ; the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License ; was not distributed with this source code in the LICENSE file, you can ; obtain it at www.aomedia.org/license/software. If the Alliance for Open ; Media Patent License 1.0 was not distributed with this source code in the ; PATENTS file, you can obtain it at www.aomedia.org/license/patent. ; ; %include "third_party/x86inc/x86inc.asm" SECTION .text %macro QUANTIZE_FN 2 cglobal quantize_%1, 0, %2, 15, coeff, ncoeff, skip, zbin, round, quant, \ shift, qcoeff, dqcoeff, dequant, \ eob, scan, iscan vzeroupper ; If we can skip this block, then just zero the output cmp skipmp, 0 jne .blank %ifnidn %1, b_32x32 ; Special case for ncoeff == 16, as it is frequent and we can save on ; not setting up a loop. cmp ncoeffmp, 16 jne .generic ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Special case of ncoeff == 16 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; .single: movifnidn coeffq, coeffmp movifnidn zbinq, zbinmp mova m0, [zbinq] ; m0 = zbin ; Get DC and first 15 AC coeffs - in this special case, that is all. %if CONFIG_HIGHBITDEPTH ; coeff stored as 32bit numbers but we process them as 16 bit numbers mova m9, [coeffq] packssdw m9, [coeffq+16] ; m9 = c[i] mova m10, [coeffq+32] packssdw m10, [coeffq+48] ; m10 = c[i] %else mova m9, [coeffq] ; m9 = c[i] mova m10, [coeffq+16] ; m10 = c[i] %endif mov r0, eobmp ; Output pointer mov r1, qcoeffmp ; Output pointer mov r2, dqcoeffmp ; Output pointer pxor m5, m5 ; m5 = dedicated zero pcmpeqw m4, m4 ; All word lanes -1 paddw m0, m4 ; m0 = zbin - 1 pabsw m6, m9 ; m6 = abs(m9) pabsw m11, m10 ; m11 = abs(m10) pcmpgtw m7, m6, m0 ; m7 = c[i] >= zbin punpckhqdq m0, m0 pcmpgtw m12, m11, m0 ; m12 = c[i] >= zbin ; Check if all coeffs are less than zbin. If yes, we just write zeros ; to the outputs and we are done. por m14, m7, m12 ptest m14, m14 jnz .single_nonzero %if CONFIG_HIGHBITDEPTH mova [r1 ], ymm5 mova [r1+32], ymm5 mova [r2 ], ymm5 mova [r2+32], ymm5 %else mova [r1], ymm5 mova [r2], ymm5 %endif mov [r0], word 0 vzeroupper RET .single_nonzero: ; Actual quantization of size 16 block - setup pointers, rounders, etc. movifnidn r4, roundmp movifnidn r5, quantmp mov r3, dequantmp mov r6, shiftmp mova m1, [r4] ; m1 = round mova m2, [r5] ; m2 = quant mova m3, [r3] ; m3 = dequant mova m4, [r6] ; m4 = shift mov r3, iscanmp DEFINE_ARGS eob, qcoeff, dqcoeff, iscan ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; paddsw m6, m1 ; m6 += round punpckhqdq m1, m1 paddsw m11, m1 ; m11 += round pmulhw m8, m6, m2 ; m8 = m6*q>>16 punpckhqdq m2, m2 pmulhw m13, m11, m2 ; m13 = m11*q>>16 paddw m8, m6 ; m8 += m6 paddw m13, m11 ; m13 += m11 pmulhw m8, m4 ; m8 = m8*qsh>>16 punpckhqdq m4, m4 pmulhw m13, m4 ; m13 = m13*qsh>>16 psignw m8, m9 ; m8 = reinsert sign psignw m13, m10 ; m13 = reinsert sign pand m8, m7 pand m13, m12 %if CONFIG_HIGHBITDEPTH ; Store 16bit numbers as 32bit numbers in array pointed to by qcoeff pcmpgtw m6, m5, m8 punpckhwd m6, m8, m6 pmovsxwd m11, m8 mova [qcoeffq ], m11 mova [qcoeffq+16], m6 pcmpgtw m6, m5, m13 punpckhwd m6, m13, m6 pmovsxwd m11, m13 mova [qcoeffq+32], m11 mova [qcoeffq+48], m6 %else mova [qcoeffq ], m8 mova [qcoeffq+16], m13 %endif pmullw m8, m3 ; dqc[i] = qc[i] * q punpckhqdq m3, m3 pmullw m13, m3 ; dqc[i] = qc[i] * q %if CONFIG_HIGHBITDEPTH ; Store 16bit numbers as 32bit numbers in array pointed to by qcoeff pcmpgtw m6, m5, m8 punpckhwd m6, m8, m6 pmovsxwd m11, m8 mova [dqcoeffq ], m11 mova [dqcoeffq+16], m6 pcmpgtw m6, m5, m13 punpckhwd m6, m13, m6 pmovsxwd m11, m13 mova [dqcoeffq+32], m11 mova [dqcoeffq+48], m6 %else mova [dqcoeffq ], m8 mova [dqcoeffq+16], m13 %endif mova m6, [iscanq] ; m6 = scan[i] mova m11, [iscanq+16] ; m11 = scan[i] pcmpeqw m8, m8, m5 ; m8 = c[i] == 0 pcmpeqw m13, m13, m5 ; m13 = c[i] == 0 psubw m6, m6, m7 ; m6 = scan[i] + 1 psubw m11, m11, m12 ; m11 = scan[i] + 1 pandn m8, m8, m6 ; m8 = max(eob) pandn m13, m13, m11 ; m13 = max(eob) pmaxsw m8, m8, m13 ; Horizontally accumulate/max eobs and write into [eob] memory pointer pshufd m7, m8, 0xe pmaxsw m8, m7 pshuflw m7, m8, 0xe pmaxsw m8, m7 pshuflw m7, m8, 0x1 pmaxsw m8, m7 movq rax, m8 mov [eobq], ax vzeroupper RET ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Generic case of ncoeff != 16 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; .generic: %endif ; %ifnidn %1, b_32x32 DEFINE_ARGS coeff, ncoeff, skip, zbin, round, quant, shift, \ qcoeff, dqcoeff, dequant, eob, scan, iscan ; Actual quantization loop - setup pointers, rounders, etc. movifnidn coeffq, coeffmp movifnidn ncoeffq, ncoeffmp mov r2, dequantmp movifnidn zbinq, zbinmp movifnidn roundq, roundmp movifnidn quantq, quantmp mova m0, [zbinq] ; m0 = zbin mova m1, [roundq] ; m1 = round mova m2, [quantq] ; m2 = quant mova m3, [r2] ; m3 = dequant pcmpeqw m4, m4 ; All lanes -1 %ifidn %1, b_32x32 psubw m0, m4 psubw m1, m4 psrlw m0, 1 ; m0 = (m0 + 1) / 2 psrlw m1, 1 ; m1 = (m1 + 1) / 2 %endif paddw m0, m4 ; m0 = m0 + 1 mov r2, shiftmp mov r3, qcoeffmp mova m4, [r2] ; m4 = shift mov r4, dqcoeffmp mov r5, iscanmp %ifidn %1, b_32x32 psllw m4, 1 %endif pxor m5, m5 ; m5 = dedicated zero DEFINE_ARGS coeff, ncoeff, d1, qcoeff, dqcoeff, iscan, d2, d3, d4, d5, eob %if CONFIG_HIGHBITDEPTH lea coeffq, [ coeffq+ncoeffq*4] lea qcoeffq, [ qcoeffq+ncoeffq*4] lea dqcoeffq, [dqcoeffq+ncoeffq*4] %else lea coeffq, [ coeffq+ncoeffq*2] lea qcoeffq, [ qcoeffq+ncoeffq*2] lea dqcoeffq, [dqcoeffq+ncoeffq*2] %endif lea iscanq, [ iscanq+ncoeffq*2] neg ncoeffq ; get DC and first 15 AC coeffs %if CONFIG_HIGHBITDEPTH ; coeff stored as 32bit numbers & require 16bit numbers mova m9, [coeffq+ncoeffq*4+ 0] packssdw m9, [coeffq+ncoeffq*4+16] mova m10, [coeffq+ncoeffq*4+32] packssdw m10, [coeffq+ncoeffq*4+48] %else mova m9, [coeffq+ncoeffq*2+ 0] ; m9 = c[i] mova m10, [coeffq+ncoeffq*2+16] ; m10 = c[i] %endif pabsw m6, m9 ; m6 = abs(m9) pabsw m11, m10 ; m11 = abs(m10) pcmpgtw m7, m6, m0 ; m7 = c[i] >= zbin punpckhqdq m0, m0 pcmpgtw m12, m11, m0 ; m12 = c[i] >= zbin ; Check if all coeffs are less than zbin. If yes, skip forward quickly. por m14, m7, m12 ptest m14, m14 jnz .first_nonzero %if CONFIG_HIGHBITDEPTH mova [qcoeffq+ncoeffq*4 ], ymm5 mova [qcoeffq+ncoeffq*4+32], ymm5 mova [dqcoeffq+ncoeffq*4 ], ymm5 mova [dqcoeffq+ncoeffq*4+32], ymm5 %else mova [qcoeffq+ncoeffq*2], ymm5 mova [dqcoeffq+ncoeffq*2], ymm5 %endif add ncoeffq, mmsize punpckhqdq m1, m1 punpckhqdq m2, m2 punpckhqdq m3, m3 punpckhqdq m4, m4 pxor m8, m8 jmp .ac_only_loop .first_nonzero: paddsw m6, m1 ; m6 += round punpckhqdq m1, m1 paddsw m11, m1 ; m11 += round pmulhw m8, m6, m2 ; m8 = m6*q>>16 punpckhqdq m2, m2 pmulhw m13, m11, m2 ; m13 = m11*q>>16 paddw m8, m6 ; m8 += m6 paddw m13, m11 ; m13 += m11 pmulhw m8, m4 ; m8 = m8*qsh>>16 punpckhqdq m4, m4 pmulhw m13, m4 ; m13 = m13*qsh>>16 psignw m8, m9 ; m8 = reinsert sign psignw m13, m10 ; m13 = reinsert sign pand m8, m7 pand m13, m12 %if CONFIG_HIGHBITDEPTH ; store 16bit numbers as 32bit numbers in array pointed to by qcoeff pcmpgtw m6, m5, m8 punpckhwd m6, m8, m6 pmovsxwd m11, m8 mova [qcoeffq+ncoeffq*4+ 0], m11 mova [qcoeffq+ncoeffq*4+16], m6 pcmpgtw m6, m5, m13 punpckhwd m6, m13, m6 pmovsxwd m11, m13 mova [qcoeffq+ncoeffq*4+32], m11 mova [qcoeffq+ncoeffq*4+48], m6 %else mova [qcoeffq+ncoeffq*2+ 0], m8 mova [qcoeffq+ncoeffq*2+16], m13 %endif %ifidn %1, b_32x32 pabsw m8, m8 pabsw m13, m13 %endif pmullw m8, m3 ; dqc[i] = qc[i] * q punpckhqdq m3, m3 pmullw m13, m3 ; dqc[i] = qc[i] * q %ifidn %1, b_32x32 psrlw m8, 1 psrlw m13, 1 psignw m8, m9 psignw m13, m10 %endif %if CONFIG_HIGHBITDEPTH ; store 16bit numbers as 32bit numbers in array pointed to by qcoeff pcmpgtw m6, m5, m8 punpckhwd m6, m8, m6 pmovsxwd m11, m8 mova [dqcoeffq+ncoeffq*4+ 0], m11 mova [dqcoeffq+ncoeffq*4+16], m6 pcmpgtw m6, m5, m13 punpckhwd m6, m13, m6 pmovsxwd m11, m13 mova [dqcoeffq+ncoeffq*4+32], m11 mova [dqcoeffq+ncoeffq*4+48], m6 %else mova [dqcoeffq+ncoeffq*2+ 0], m8 mova [dqcoeffq+ncoeffq*2+16], m13 %endif pcmpeqw m8, m5 ; m8 = c[i] == 0 pcmpeqw m13, m5 ; m13 = c[i] == 0 mova m6, [iscanq+ncoeffq*2] ; m6 = scan[i] mova m11, [iscanq+ncoeffq*2+16] ; m11 = scan[i] psubw m6, m7 ; m6 = scan[i] + 1 psubw m11, m12 ; m11 = scan[i] + 1 pandn m8, m6 ; m8 = max(eob) pandn m13, m11 ; m13 = max(eob) pmaxsw m8, m13 add ncoeffq, mmsize .ac_only_loop: %if CONFIG_HIGHBITDEPTH ; pack coeff from 32bit to 16bit array mova m9, [coeffq+ncoeffq*4+ 0] packssdw m9, [coeffq+ncoeffq*4+16] mova m10, [coeffq+ncoeffq*4+32] packssdw m10, [coeffq+ncoeffq*4+48] %else mova m9, [coeffq+ncoeffq*2+ 0] ; m9 = c[i] mova m10, [coeffq+ncoeffq*2+16] ; m10 = c[i] %endif pabsw m6, m9 ; m6 = abs(m9) pabsw m11, m10 ; m11 = abs(m10) pcmpgtw m7, m6, m0 ; m7 = c[i] >= zbin pcmpgtw m12, m11, m0 ; m12 = c[i] >= zbin ; Check if all coeffs are less than zbin. If yes, skip this itertion. ; And just write zeros as the result would be. por m14, m7, m12 ptest m14, m14 jnz .rest_nonzero %if CONFIG_HIGHBITDEPTH mova [qcoeffq+ncoeffq*4+ 0], ymm5 mova [qcoeffq+ncoeffq*4+32], ymm5 mova [dqcoeffq+ncoeffq*4+ 0], ymm5 mova [dqcoeffq+ncoeffq*4+32], ymm5 %else mova [qcoeffq+ncoeffq*2+ 0], ymm5 mova [dqcoeffq+ncoeffq*2+ 0], ymm5 %endif add ncoeffq, mmsize jnz .ac_only_loop ; Horizontally accumulate/max eobs and write into [eob] memory pointer mov r2, eobmp pshufd m7, m8, 0xe pmaxsw m8, m7 pshuflw m7, m8, 0xe pmaxsw m8, m7 pshuflw m7, m8, 0x1 pmaxsw m8, m7 movq rax, m8 mov [r2], ax vzeroupper RET .rest_nonzero: paddsw m6, m1 ; m6 += round paddsw m11, m1 ; m11 += round pmulhw m14, m6, m2 ; m14 = m6*q>>16 pmulhw m13, m11, m2 ; m13 = m11*q>>16 paddw m14, m6 ; m14 += m6 paddw m13, m11 ; m13 += m11 pmulhw m14, m4 ; m14 = m14*qsh>>16 pmulhw m13, m4 ; m13 = m13*qsh>>16 psignw m14, m9 ; m14 = reinsert sign psignw m13, m10 ; m13 = reinsert sign pand m14, m7 pand m13, m12 %if CONFIG_HIGHBITDEPTH ; store 16bit numbers as 32bit numbers in array pointed to by qcoeff pcmpgtw m6, m5, m14 punpckhwd m6, m14, m6 pmovsxwd m11, m14 mova [qcoeffq+ncoeffq*4+ 0], m11 mova [qcoeffq+ncoeffq*4+16], m6 pcmpgtw m6, m5, m13 punpckhwd m6, m13, m6 pmovsxwd m11, m13 mova [qcoeffq+ncoeffq*4+32], m11 mova [qcoeffq+ncoeffq*4+48], m6 %else mova [qcoeffq+ncoeffq*2+ 0], m14 mova [qcoeffq+ncoeffq*2+16], m13 %endif %ifidn %1, b_32x32 pabsw m14, m14 pabsw m13, m13 %endif pmullw m14, m3 ; dqc[i] = qc[i] * q pmullw m13, m3 ; dqc[i] = qc[i] * q %ifidn %1, b_32x32 psrlw m14, 1 psrlw m13, 1 psignw m14, m9 psignw m13, m10 %endif %if CONFIG_HIGHBITDEPTH ; store 16bit numbers as 32bit numbers in array pointed to by qcoeff pcmpgtw m6, m5, m14 punpckhwd m6, m14, m6 pmovsxwd m11, m14 mova [dqcoeffq+ncoeffq*4+ 0], m11 mova [dqcoeffq+ncoeffq*4+16], m6 pcmpgtw m6, m5, m13 punpckhwd m6, m13, m6 pmovsxwd m11, m13 mova [dqcoeffq+ncoeffq*4+32], m11 mova [dqcoeffq+ncoeffq*4+48], m6 %else mova [dqcoeffq+ncoeffq*2+ 0], m14 mova [dqcoeffq+ncoeffq*2+16], m13 %endif pcmpeqw m14, m5 ; m14 = c[i] == 0 pcmpeqw m13, m5 ; m13 = c[i] == 0 mova m6, [iscanq+ncoeffq*2+ 0] ; m6 = scan[i] mova m11, [iscanq+ncoeffq*2+16] ; m11 = scan[i] psubw m6, m7 ; m6 = scan[i] + 1 psubw m11, m12 ; m11 = scan[i] + 1 pandn m14, m6 ; m14 = max(eob) pandn m13, m11 ; m13 = max(eob) pmaxsw m8, m14 pmaxsw m8, m13 add ncoeffq, mmsize jnz .ac_only_loop ; Horizontally accumulate/max eobs and write into [eob] memory pointer mov r2, eobmp pshufd m7, m8, 0xe pmaxsw m8, m7 pshuflw m7, m8, 0xe pmaxsw m8, m7 pshuflw m7, m8, 0x1 pmaxsw m8, m7 movq rax, m8 mov [r2], ax vzeroupper RET ; Skip-block, i.e. just write all zeroes .blank: DEFINE_ARGS coeff, ncoeff, skip, zbin, round, quant, shift, \ qcoeff, dqcoeff, dequant, eob, scan, iscan mov r0, dqcoeffmp movifnidn ncoeffq, ncoeffmp mov r2, qcoeffmp mov r3, eobmp DEFINE_ARGS dqcoeff, ncoeff, qcoeff, eob %if CONFIG_HIGHBITDEPTH lea dqcoeffq, [dqcoeffq+ncoeffq*4] lea qcoeffq, [ qcoeffq+ncoeffq*4] %else lea dqcoeffq, [dqcoeffq+ncoeffq*2] lea qcoeffq, [ qcoeffq+ncoeffq*2] %endif neg ncoeffq pxor m7, m7 .blank_loop: %if CONFIG_HIGHBITDEPTH mova [dqcoeffq+ncoeffq*4+ 0], ymm7 mova [dqcoeffq+ncoeffq*4+32], ymm7 mova [qcoeffq+ncoeffq*4+ 0], ymm7 mova [qcoeffq+ncoeffq*4+32], ymm7 %else mova [dqcoeffq+ncoeffq*2+ 0], ymm7 mova [qcoeffq+ncoeffq*2+ 0], ymm7 %endif add ncoeffq, mmsize jl .blank_loop mov [eobq], word 0 vzeroupper RET %endmacro INIT_XMM avx QUANTIZE_FN b, 7 QUANTIZE_FN b_32x32, 7 END
; void adt_StackDelete(struct adt_Stack *s, void *delete) ; CALLER linkage for function pointers SECTION code_clib PUBLIC adt_StackDelete PUBLIC _adt_StackDelete EXTERN adt_StackDelete_callee EXTERN ASMDISP_ADT_STACKDELETE_CALLEE .adt_StackDelete ._adt_StackDelete pop bc pop de pop hl push hl push de push bc jp adt_StackDelete_callee + ASMDISP_ADT_STACKDELETE_CALLEE
# just another program .data datay : .float 0.0 data1 : .float 2.0 data2 : .float 3.0 datam : .float 3.14 datan : .float 1.45 .text main: l.s $f0, data1 l.s $f1, data2 l.s $f2, datam l.s $f3, datan mul.s $f4, $f2, $f0 div.s $f5, $f3, $f1 add.s $f4, $f4, $f5 s.s $f4, datay li $v0, 10 syscall
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/webview/web_dialog_view.h" #include <vector> #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "ui/events/event.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/root_view.h" #include "ui/views/widget/widget.h" #include "ui/web_dialogs/web_dialog_delegate.h" #include "ui/web_dialogs/web_dialog_ui.h" using content::NativeWebKeyboardEvent; using content::WebContents; using content::WebUIMessageHandler; using ui::WebDialogDelegate; using ui::WebDialogUI; using ui::WebDialogWebContentsDelegate; namespace views { //////////////////////////////////////////////////////////////////////////////// // WebDialogView, public: WebDialogView::WebDialogView( content::BrowserContext* context, WebDialogDelegate* delegate, WebContentsHandler* handler) : ClientView(NULL, NULL), WebDialogWebContentsDelegate(context, handler), delegate_(delegate), web_view_(new views::WebView(context)), is_attempting_close_dialog_(false), before_unload_fired_(false), closed_via_webui_(false), close_contents_called_(false) { web_view_->set_allow_accelerators(true); AddChildView(web_view_); set_contents_view(web_view_); SetLayoutManager(new views::FillLayout); // Pressing the ESC key will close the dialog. AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE)); } WebDialogView::~WebDialogView() { } content::WebContents* WebDialogView::web_contents() { return web_view_->web_contents(); } //////////////////////////////////////////////////////////////////////////////// // WebDialogView, views::View implementation: gfx::Size WebDialogView::GetPreferredSize() const { gfx::Size out; if (delegate_) delegate_->GetDialogSize(&out); return out; } gfx::Size WebDialogView::GetMinimumSize() const { gfx::Size out; if (delegate_) delegate_->GetMinimumDialogSize(&out); return out; } bool WebDialogView::AcceleratorPressed(const ui::Accelerator& accelerator) { // Pressing ESC closes the dialog. DCHECK_EQ(ui::VKEY_ESCAPE, accelerator.key_code()); if (GetWidget()) GetWidget()->Close(); return true; } void WebDialogView::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.is_add && GetWidget()) InitDialog(); } bool WebDialogView::CanClose() { // Don't close UI if |delegate_| does not allow users to close it by // clicking on "x" button or pressing Esc shortcut key on hosting dialog. if (!delegate_->CanCloseDialog() && !close_contents_called_) return false; // If CloseContents() is called before CanClose(), which is called by // RenderViewHostImpl::ClosePageIgnoringUnloadEvents, it indicates // beforeunload event should not be fired during closing. if ((is_attempting_close_dialog_ && before_unload_fired_) || close_contents_called_) { is_attempting_close_dialog_ = false; before_unload_fired_ = false; return true; } if (!is_attempting_close_dialog_) { // Fire beforeunload event when user attempts to close the dialog. is_attempting_close_dialog_ = true; web_view_->web_contents()->DispatchBeforeUnload(false); } return false; } //////////////////////////////////////////////////////////////////////////////// // WebDialogView, views::WidgetDelegate implementation: bool WebDialogView::CanResize() const { if (delegate_) return delegate_->CanResizeDialog(); return true; } ui::ModalType WebDialogView::GetModalType() const { return GetDialogModalType(); } base::string16 WebDialogView::GetWindowTitle() const { if (delegate_) return delegate_->GetDialogTitle(); return base::string16(); } std::string WebDialogView::GetWindowName() const { if (delegate_) return delegate_->GetDialogName(); return std::string(); } void WebDialogView::WindowClosing() { // If we still have a delegate that means we haven't notified it of the // dialog closing. This happens if the user clicks the Close button on the // dialog. if (delegate_) OnDialogClosed(""); } views::View* WebDialogView::GetContentsView() { return this; } views::ClientView* WebDialogView::CreateClientView(views::Widget* widget) { return this; } views::View* WebDialogView::GetInitiallyFocusedView() { return web_view_; } bool WebDialogView::ShouldShowWindowTitle() const { return ShouldShowDialogTitle(); } views::Widget* WebDialogView::GetWidget() { return View::GetWidget(); } const views::Widget* WebDialogView::GetWidget() const { return View::GetWidget(); } //////////////////////////////////////////////////////////////////////////////// // WebDialogDelegate implementation: ui::ModalType WebDialogView::GetDialogModalType() const { if (delegate_) return delegate_->GetDialogModalType(); return ui::MODAL_TYPE_NONE; } base::string16 WebDialogView::GetDialogTitle() const { return GetWindowTitle(); } GURL WebDialogView::GetDialogContentURL() const { if (delegate_) return delegate_->GetDialogContentURL(); return GURL(); } void WebDialogView::GetWebUIMessageHandlers( std::vector<WebUIMessageHandler*>* handlers) const { if (delegate_) delegate_->GetWebUIMessageHandlers(handlers); } void WebDialogView::GetDialogSize(gfx::Size* size) const { if (delegate_) delegate_->GetDialogSize(size); } void WebDialogView::GetMinimumDialogSize(gfx::Size* size) const { if (delegate_) delegate_->GetMinimumDialogSize(size); } std::string WebDialogView::GetDialogArgs() const { if (delegate_) return delegate_->GetDialogArgs(); return std::string(); } void WebDialogView::OnDialogShown(content::WebUI* webui, content::RenderViewHost* render_view_host) { if (delegate_) delegate_->OnDialogShown(webui, render_view_host); } void WebDialogView::OnDialogClosed(const std::string& json_retval) { Detach(); if (delegate_) { // Store the dialog content area size. delegate_->StoreDialogSize(GetContentsBounds().size()); } if (GetWidget()) GetWidget()->Close(); if (delegate_) { delegate_->OnDialogClosed(json_retval); delegate_ = NULL; // We will not communicate further with the delegate. } } void WebDialogView::OnDialogCloseFromWebUI(const std::string& json_retval) { closed_via_webui_ = true; dialog_close_retval_ = json_retval; if (GetWidget()) GetWidget()->Close(); } void WebDialogView::OnCloseContents(WebContents* source, bool* out_close_dialog) { if (delegate_) delegate_->OnCloseContents(source, out_close_dialog); } bool WebDialogView::ShouldShowDialogTitle() const { if (delegate_) return delegate_->ShouldShowDialogTitle(); return true; } bool WebDialogView::HandleContextMenu( const content::ContextMenuParams& params) { if (delegate_) return delegate_->HandleContextMenu(params); return WebDialogWebContentsDelegate::HandleContextMenu(params); } //////////////////////////////////////////////////////////////////////////////// // content::WebContentsDelegate implementation: void WebDialogView::MoveContents(WebContents* source, const gfx::Rect& pos) { // The contained web page wishes to resize itself. We let it do this because // if it's a dialog we know about, we trust it not to be mean to the user. GetWidget()->SetBounds(pos); } // A simplified version of BrowserView::HandleKeyboardEvent(). // We don't handle global keyboard shortcuts here, but that's fine since // they're all browser-specific. (This may change in the future.) void WebDialogView::HandleKeyboardEvent(content::WebContents* source, const NativeWebKeyboardEvent& event) { if (!event.os_event) return; GetWidget()->native_widget_private()->RepostNativeEvent(event.os_event); } void WebDialogView::CloseContents(WebContents* source) { close_contents_called_ = true; bool close_dialog = false; OnCloseContents(source, &close_dialog); if (close_dialog) OnDialogClosed(closed_via_webui_ ? dialog_close_retval_ : std::string()); } content::WebContents* WebDialogView::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { content::WebContents* new_contents = NULL; if (delegate_ && delegate_->HandleOpenURLFromTab(source, params, &new_contents)) { return new_contents; } return WebDialogWebContentsDelegate::OpenURLFromTab(source, params); } void WebDialogView::AddNewContents(content::WebContents* source, content::WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture, bool* was_blocked) { if (delegate_ && delegate_->HandleAddNewContents( source, new_contents, disposition, initial_pos, user_gesture)) { return; } WebDialogWebContentsDelegate::AddNewContents( source, new_contents, disposition, initial_pos, user_gesture, was_blocked); } void WebDialogView::LoadingStateChanged(content::WebContents* source, bool to_different_document) { if (delegate_) delegate_->OnLoadingStateChanged(source); } void WebDialogView::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { before_unload_fired_ = true; *proceed_to_fire_unload = proceed; } //////////////////////////////////////////////////////////////////////////////// // WebDialogView, private: void WebDialogView::InitDialog() { content::WebContents* web_contents = web_view_->GetWebContents(); if (web_contents->GetDelegate() == this) return; web_contents->SetDelegate(this); // Set the delegate. This must be done before loading the page. See // the comment above WebDialogUI in its header file for why. WebDialogUI::SetDelegate(web_contents, this); web_view_->LoadInitialURL(GetDialogContentURL()); } } // namespace views
;; ;; Copyright (c) 2018, Intel Corporation ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, ;; this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; * Neither the name of Intel Corporation nor the names of its contributors ;; may be used to endorse or promote products derived from this software ;; without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; %include "include/aesni_emu.inc" %define AES_CBC_ENC_X4 aes_cbc_enc_192_x4_no_aesni %include "sse/aes_cbc_enc_192_x4.asm"
/* Copyright 2012-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "InMemoryView.h" #include "watchman.h" #include "watchman_error_category.h" using namespace watchman; namespace { class NeedRecrawl : public std::runtime_error { public: using std::runtime_error::runtime_error; }; } // namespace bool watchman_root::syncToNow(std::chrono::milliseconds timeout) { w_perf_t sample("sync_to_now"); bool res; try { res = view()->syncToNow(timeout); } catch (const NeedRecrawl& exc) { scheduleRecrawl(exc.what()); return false; } // We want to know about all timeouts if (!res) { sample.force_log(); } if (sample.finish()) { sample.add_root_meta(shared_from_this()); sample.add_meta( "sync_to_now", json_object({{"success", json_boolean(res)}, {"timeoutms", json_integer(timeout.count())}})); sample.log(); } return res; } /* Ensure that we're synchronized with the state of the * filesystem at the current time. * We do this by touching a cookie file and waiting to * observe it via inotify. When we see it we know that * we've seen everything up to the point in time at which * we're asking questions. * Returns true if we observe the change within the requested * time, false otherwise. */ bool watchman::InMemoryView::syncToNow(std::chrono::milliseconds timeout) { try { return cookies_.syncToNow(timeout); } catch (const std::system_error& exc) { // Note that timeouts in syncToNow are reported as a `false` return // value, so if we get any exception here then something must be // really wrong. In practice the most likely cause is that // the cookie dir no longer exists. The sanest sounding thing // to do in this situation is schedule a recrawl. if (exc.code() == watchman::error_code::no_such_file_or_directory || exc.code() == watchman::error_code::not_a_directory) { if (cookies_.cookieDir() == root_path) { throw NeedRecrawl("root dir was removed and we didn't get notified"); } else { // The cookie dir was a VCS subdir and it got deleted. Let's // focus instead on the parent dir and recursively retry. cookies_.setCookieDir(root_path); return cookies_.syncToNow(timeout); } } throw; } } /* vim:ts=2:sw=2:et: */
; =============================================================== ; Mar 2014 ; =============================================================== ; ; void b_array_destroy(b_array_t *a) ; ; Zero the array structure. ; array.capacity = 0 ensures no array operations can be performed. ; ; =============================================================== SECTION code_clib SECTION code_adt_b_array PUBLIC asm_b_array_destroy EXTERN l_setmem_hl asm_b_array_destroy: ; enter : hl = array * ; ; uses : af, hl xor a jp l_setmem_hl - 12
;dx: dh = number of sectors to read, dl = num of drive ;we will read our word from disk to address in bx disk_load: pusha push dx ;we will overwrite input parameter in dx, so let's save it on stack ;set up inputs for 0x13 disk IO interrupt mov ah, 0x02 ;0x2 is read mode mov al, dh ;set number of sectors to read mov cl, 0x02 ;select sector 2 mov ch, 0x00 ;select cylinder 0 mov dh, 0x0 ;select head 0 -> we just modified our input register dx, this is why we saved it to stack earlier ;[es: bx] will be the pointer to our buffer to where the interrupt will put the read data from disk ;caller sets bx int 0x13 ;initiate disk read jc disk_error ;if error occurs, carry bit is set, jump to error handling pop dx ;get back dx, so we will have our input params back dh = number of sectors read, dl = num of drive cmp al, dh ;check how many sectors we read jne sectors_error ;sector reading error handling popa ret disk_error: mov bx, DISK_ERROR call print call print_nl mov dh, ah ;get error code call print_hex jmp disk_loop sectors_error: mov bx, SECTOR_ERROR call print disk_loop: jmp $ DISK_ERROR: db 'Error reading from disk', 0 SECTOR_ERROR: db 'Error reading sectors', 0
############################################################################### # Copyright 2018 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .text .p2align 4, 0x90 .globl _DecryptCBC_RIJ128pipe_AES_NI _DecryptCBC_RIJ128pipe_AES_NI: push %ebp mov %esp, %ebp push %ebx push %esi push %edi movl (8)(%ebp), %esi movl (12)(%ebp), %edi movl (20)(%ebp), %ecx movl (16)(%ebp), %eax sub $(96), %esp lea (16)(%esp), %edx and $(-16), %edx movl (28)(%ebp), %ebx movdqu (%ebx), %xmm4 movdqa %xmm4, (%edx) subl $(64), (24)(%ebp) jl .Lshort_inputgas_1 lea (,%eax,4), %ebx lea (%ecx,%ebx,4), %ecx .Lblks_loopgas_1: movdqa (%ecx), %xmm4 lea (-16)(%ecx), %ebx movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu (32)(%esi), %xmm2 movdqu (48)(%esi), %xmm3 movdqa %xmm0, (16)(%edx) movdqa %xmm1, (32)(%edx) movdqa %xmm2, (48)(%edx) movdqa %xmm3, (64)(%edx) pxor %xmm4, %xmm0 pxor %xmm4, %xmm1 pxor %xmm4, %xmm2 pxor %xmm4, %xmm3 movdqa (%ebx), %xmm4 sub $(16), %ebx movl (16)(%ebp), %eax sub $(1), %eax .Lcipher_loopgas_1: aesdec %xmm4, %xmm0 aesdec %xmm4, %xmm1 aesdec %xmm4, %xmm2 aesdec %xmm4, %xmm3 movdqa (%ebx), %xmm4 sub $(16), %ebx dec %eax jnz .Lcipher_loopgas_1 aesdeclast %xmm4, %xmm0 pxor (%edx), %xmm0 movdqu %xmm0, (%edi) aesdeclast %xmm4, %xmm1 pxor (16)(%edx), %xmm1 movdqu %xmm1, (16)(%edi) aesdeclast %xmm4, %xmm2 pxor (32)(%edx), %xmm2 movdqu %xmm2, (32)(%edi) aesdeclast %xmm4, %xmm3 pxor (48)(%edx), %xmm3 movdqu %xmm3, (48)(%edi) movdqa (64)(%edx), %xmm4 movdqa %xmm4, (%edx) add $(64), %esi add $(64), %edi subl $(64), (24)(%ebp) jge .Lblks_loopgas_1 .Lshort_inputgas_1: addl $(64), (24)(%ebp) jz .Lquitgas_1 movl (16)(%ebp), %eax movl (20)(%ebp), %ecx lea (,%eax,4), %ebx lea (%ecx,%ebx,4), %ebx .Lsingle_blk_loopgas_1: movdqu (%esi), %xmm0 movdqa %xmm0, (16)(%edx) pxor (%ebx), %xmm0 cmp $(12), %eax jl .Lkey_128_sgas_1 jz .Lkey_192_sgas_1 .Lkey_256_sgas_1: aesdec (208)(%ecx), %xmm0 aesdec (192)(%ecx), %xmm0 .Lkey_192_sgas_1: aesdec (176)(%ecx), %xmm0 aesdec (160)(%ecx), %xmm0 .Lkey_128_sgas_1: aesdec (144)(%ecx), %xmm0 aesdec (128)(%ecx), %xmm0 aesdec (112)(%ecx), %xmm0 aesdec (96)(%ecx), %xmm0 aesdec (80)(%ecx), %xmm0 aesdec (64)(%ecx), %xmm0 aesdec (48)(%ecx), %xmm0 aesdec (32)(%ecx), %xmm0 aesdec (16)(%ecx), %xmm0 aesdeclast (%ecx), %xmm0 pxor (%edx), %xmm0 movdqu %xmm0, (%edi) movdqa (16)(%edx), %xmm4 movdqa %xmm4, (%edx) add $(16), %esi add $(16), %edi subl $(16), (24)(%ebp) jnz .Lsingle_blk_loopgas_1 .Lquitgas_1: add $(96), %esp pop %edi pop %esi pop %ebx pop %ebp ret
; A195317: Centered 40-gonal numbers. ; 1,41,121,241,401,601,841,1121,1441,1801,2201,2641,3121,3641,4201,4801,5441,6121,6841,7601,8401,9241,10121,11041,12001,13001,14041,15121,16241,17401,18601,19841,21121,22441,23801,25201,26641,28121,29641,31201,32801,34441,36121,37841,39601,41401,43241,45121,47041,49001,51001,53041,55121,57241,59401,61601,63841,66121,68441,70801,73201,75641,78121,80641,83201,85801,88441,91121,93841,96601,99401,102241,105121,108041,111001,114001,117041,120121,123241,126401,129601,132841,136121,139441,142801,146201,149641,153121,156641,160201,163801,167441,171121,174841,178601,182401,186241,190121,194041,198001 sub $1,$0 bin $1,2 mul $1,40 add $1,1 mov $0,$1
.text .file "h264ref.memalloc.no_mem_exit.ll" .globl no_mem_exit .align 16 .type no_mem_exit,@function no_mem_exit: // @no_mem_exit // BB#0: { r2 = ##.str.20 r3 = r0 allocframe(#8) } { r1 = #300 r0 = ##errortext memw(r29 + #0) = r3 } { call snprintf } { r1:0 = combine(#100, ##errortext) deallocframe } { jump error } .Lfunc_end0: .size no_mem_exit, .Lfunc_end0-no_mem_exit .hidden .str.20 .ident "clang version 3.8.0 (http://llvm.org/git/clang.git 2d49f0a0ae8366964a93e3b7b26e29679bee7160) (http://llvm.org/git/llvm.git 60bc66b44837125843b58ed3e0fd2e6bb948d839)" .section ".note.GNU-stack","",@progbits
// myextension.cpp // Extension lib defines #define LIB_NAME "ImGui" #define MODULE_NAME "imgui" #include <stdlib.h> #include <vector> #include "imgui/imgui.h" #include "imgui/imconfig.h" #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) #include <GL/gl3w.h> #endif // include the Defold SDK #include <dmsdk/sdk.h> #include <dmsdk/dlib/crypt.h> #if defined(DM_PLATFORM_ANDROID) #include "imgui/imgui_impl_android.h" #endif #include "imgui/imgui_impl_opengl3.h" #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_STATIC #include "imgui/stb_image.h" #define MAX_HISTOGRAM_VALUES 1000 * 1024 #define MAX_IMAGE_NAME 256 #define TEXTBUFFER_SIZE sizeof(char) * 1000 * 1024 static bool g_imgui_NewFrame = false; static char* g_imgui_TextBuffer = 0; // ---------------------------- // ----- IMAGES --------------- // ---------------------------- // extern unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp); // typedef struct ImgObject { int w; int h; int comp; GLuint tid; char name[MAX_IMAGE_NAME]; unsigned char * data; } ImgObject; static std::vector<ImFont *> fonts; static std::vector<ImgObject> images; static int imgui_ImageB64Decode(lua_State *L) { DM_LUA_STACK_CHECK(L, 1); const char *data = luaL_checkstring(L,1); uint32_t datalen = luaL_checknumber(L,2); uint32_t dstlen = 4*(datalen/3 + 1); char *datastr = (char *)malloc(dstlen); bool result; result = dmCrypt::Base64Decode((const uint8_t*)data, datalen, (uint8_t*)datastr, &dstlen); lua_pushlstring(L, datastr, dstlen); free(datastr); return 1; } static int imgui_ImageInternalLoad(const char *filename, ImgObject *iobj) { if(iobj->data == nullptr) { dmLogError("Error loading image: %s\n", filename); return -1; } glGenTextures(1, &iobj->tid); glBindTexture(GL_TEXTURE_2D, iobj->tid); strcpy(iobj->name, filename); images.push_back(*iobj); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // This is required on WebGL for non power-of-two textures glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Same glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, iobj->w, iobj->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, iobj->data); return images.size()-1; } // Image handling needs to be smarter, but this will do for the time being. static int imgui_ImageLoadData(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); const char * filename = luaL_checkstring(L, 1); // If its already in the vector, return the id for(int i=0; i<images.size(); i++) { if(strcmp(images[i].name, filename) == 0) { lua_pushinteger(L, i); return 1; } } ImgObject iobj; unsigned char *strdata = (unsigned char *)luaL_checkstring(L, 2); int lendata = luaL_checkinteger(L, 3); iobj.data = stbi_load_from_memory( strdata, lendata, &iobj.w, &iobj.h, NULL, STBI_rgb_alpha); //dmLogError("Loaded Image: %s %d %d \n", filename, iobj.w, iobj.h); if(iobj.data == nullptr) { dmLogError("Error loading image: %s\n", filename); lua_pushnil(L); return 1; } int idx = imgui_ImageInternalLoad(filename, &iobj); if(idx < 0) { lua_pushnil(L); return 1; } stbi_image_free(iobj.data); iobj.data = NULL; lua_pushinteger(L, idx); return 1; } // Image handling needs to be smarter, but this will do for the time being. static int imgui_ImageLoad(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); const char * filename = luaL_checkstring(L, 1); // If its already in the vector, return the id for(int i=0; i<images.size(); i++) { if(strcmp(images[i].name, filename) == 0) { lua_pushinteger(L, i); return 1; } } ImgObject iobj; iobj.data = stbi_load(filename, &iobj.w, &iobj.h, NULL, STBI_rgb_alpha); if(iobj.data == nullptr) { dmLogError("Error loading image: %s\n", filename); lua_pushnil(L); return 1; } int idx = imgui_ImageInternalLoad(filename, &iobj); if(idx < 0) { lua_pushnil(L); return 1; } stbi_image_free(iobj.data); iobj.data = NULL; lua_pushinteger(L, idx); return 1; } static int imgui_ImageGet( lua_State *L ) { DM_LUA_STACK_CHECK(L, 1); int id = luaL_checkinteger(L, 1); if(id>=0 && id <images.size()) { if(images[id].tid >= 0) lua_pushinteger(L, id); else lua_pushnil(L); } else lua_pushnil(L); return 1; } static int imgui_ImageAdd( lua_State *L ) { DM_LUA_STACK_CHECK(L, 0); int tid = luaL_checkinteger(L, 1); int w = luaL_checkinteger(L, 2); int h = luaL_checkinteger(L, 3); if(tid<0 || tid >=images.size()) return 0; ImgObject iobj = images[tid]; ImGui::Image((void*)(intptr_t)iobj.tid, ImVec2(w, h)); return 0; } static int imgui_ImageFree( lua_State *L ) { DM_LUA_STACK_CHECK(L, 0); int tid = luaL_checkinteger(L, 1); assert(tid>=0 && tid <images.size()); images[tid].tid = -1; return 0; } // ---------------------------- // ----- FRAMES --------------- // ---------------------------- static void imgui_NewFrame() { if (g_imgui_NewFrame == false) { ImGui_ImplOpenGL3_NewFrame(); ImGui::NewFrame(); g_imgui_NewFrame = true; } } static int imgui_SetDisplaySize(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); float w = luaL_checknumber(L, 1); float h = luaL_checknumber(L, 2); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(w, h); return 0; } // ---------------------------- // ----- INPUT ---------------- // ---------------------------- static int imgui_SetMouseInput(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiIO& io = ImGui::GetIO(); const ImVec2 mouse_pos_backup = io.MousePos; io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); if (io.WantSetMousePos) { return luaL_error(L, "WantSetMousePos not supported yet."); } else { io.MousePos = ImVec2(luaL_checknumber(L, 1), luaL_checknumber(L, 2)); } io.MouseDown[0] = luaL_checknumber(L, 3); io.MouseDown[1] = luaL_checknumber(L, 4); io.MouseDown[2] = luaL_checknumber(L, 5); io.MouseWheel += luaL_checknumber(L, 6); return 0; } static int imgui_SetKeyDown(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiIO& io = ImGui::GetIO(); uint32_t key = luaL_checknumber(L, 1); io.KeysDown[key] = lua_toboolean(L, 2); return 0; } // ---------------------------- // ----- KEY MODIFIERS -------- // ---------------------------- static int imgui_SetKeyModifierCtrl(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiIO& io = ImGui::GetIO(); io.KeyCtrl = lua_toboolean(L, 1); return 0; } static int imgui_SetKeyModifierShift(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiIO& io = ImGui::GetIO(); io.KeyShift = lua_toboolean(L, 1); return 0; } static int imgui_SetKeyModifierAlt(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiIO& io = ImGui::GetIO(); io.KeyAlt = lua_toboolean(L, 1); return 0; } static int imgui_SetKeyModifierSuper(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiIO& io = ImGui::GetIO(); io.KeySuper = lua_toboolean(L, 1); return 0; } // ---------------------------- // ----- TEXT INPUT ----------- // ---------------------------- static int imgui_AddInputCharacter(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiIO& io = ImGui::GetIO(); const char* s = luaL_checkstring(L, 1); unsigned int c = s[0]; io.AddInputCharacter(c); return 0; } // ---------------------------- // ----- TREE ----------------- // ---------------------------- static int imgui_TreeNode(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); imgui_NewFrame(); const char* text = luaL_checkstring(L, 1); uint32_t flags = 0; if (lua_isnumber(L, 2)) { flags = luaL_checkint(L, 2); } bool result = ImGui::TreeNodeEx(text, flags); lua_pushboolean(L, result); return 1; } static int imgui_TreePop(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::TreePop(); return 0; } // ---------------------------- // ----- WINDOW --------------- // ---------------------------- static int imgui_Begin(lua_State* L) { DM_LUA_STACK_CHECK(L, 2); imgui_NewFrame(); const char* title = luaL_checkstring(L, 1); bool is_open = true; bool* is_open_ptr = NULL; if (lua_isboolean(L, 2) && lua_toboolean(L, 2)) { is_open_ptr = &is_open; } uint32_t flags = 0; if (lua_isnumber(L, 3)) { flags = luaL_checkint(L, 3); } bool result = ImGui::Begin(title, is_open_ptr, flags); lua_pushboolean(L, result); lua_pushboolean(L, is_open); return 2; } static int imgui_End(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::End(); return 0; } static int imgui_SetNextWindowSize(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); float width = luaL_checknumber(L, 1); float height = luaL_checknumber(L, 2); ImGui::SetNextWindowSize(ImVec2(width, height)); return 0; } static int imgui_SetNextWindowPos(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); float x = luaL_checknumber(L, 1); float y = luaL_checknumber(L, 2); ImGui::SetNextWindowPos(ImVec2(x, y)); return 0; } static int imgui_IsWindowFocused(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); imgui_NewFrame(); uint32_t flags = 0; if (lua_isnumber(L, 1)) { flags = luaL_checkint(L, 1); } bool focused = ImGui::IsWindowFocused(flags); lua_pushboolean(L, focused); return 1; } // ---------------------------- // ----- CHILD WINDOW --------- // ---------------------------- static int imgui_BeginChild(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); imgui_NewFrame(); const char* title = luaL_checkstring(L, 1); float width = luaL_checknumber(L, 2); float height = luaL_checknumber(L, 3); bool border = false; if (lua_isnumber(L, 4)) border = luaL_checkinteger(L, 4) == 1; int flags = 0; if (lua_isnumber(L, 5)) flags = luaL_checknumber(L, 5); bool result = ImGui::BeginChild(title, ImVec2(width, height), border, flags); lua_pushboolean(L, result); return 1; } static int imgui_EndChild(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::EndChild(); return 0; } // ---------------------------- // ----- COMBO --------- // ---------------------------- static int imgui_BeginCombo(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); const char* preview = luaL_checkstring(L, 2); bool result = ImGui::BeginCombo(label, preview); lua_pushboolean(L, result); return 1; } static int imgui_EndCombo(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::EndCombo(); return 0; } static int imgui_Combo(lua_State* L) { DM_LUA_STACK_CHECK(L, 2); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); int current = luaL_checknumber(L, 2) - 1 ; if(!lua_istable(L, 3)) { luaL_error(L, "You must provide a table"); } const size_t len = lua_objlen(L, 3); const char* items[len]; for(int i=0; i<len; i++) { lua_pushnumber(L, i + 1); int top = lua_gettop(L); lua_gettable(L, 3); const char* item = luaL_checkstring(L, 4); items[i] = item; lua_pop(L, 1); } bool result = ImGui::Combo(label, &current, items, len); lua_pushboolean(L, result); lua_pushnumber(L, current + 1); return 2; } // ---------------------------- // ----- TABLES --------- // ---------------------------- static int imgui_BeginTable(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); imgui_NewFrame(); const char* id = luaL_checkstring(L, 1); int column = luaL_checkinteger(L, 2); bool result = ImGui::BeginTable(id, column); lua_pushboolean(L, result); return 1; } static int imgui_EndTable(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::EndTable(); return 0; } static int imgui_TableHeadersRow(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::TableHeadersRow(); return 0; } static int imgui_TableSetupColumn(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); uint32_t flags = 0; if (lua_isnumber(L, 2)) { flags = luaL_checkint(L, 2); } ImGui::TableSetupColumn(label, flags); return 0; } static int imgui_TableSetColumnIndex(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); int column = luaL_checkinteger(L, 1); ImGui::TableSetColumnIndex(column); return 0; } static int imgui_TableNextColumn(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::TableNextColumn(); return 0; } static int imgui_TableNextRow(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::TableNextRow(); return 0; } // ---------------------------- // ----- TAB BAR --------- // ---------------------------- static int imgui_BeginTabBar(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); imgui_NewFrame(); const char* id = luaL_checkstring(L, 1); bool result = ImGui::BeginTabBar(id); lua_pushboolean(L, result); return 1; } static int imgui_EndTabBar(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::EndTabBar(); return 0; } static int imgui_BeginTabItem(lua_State* L) { DM_LUA_STACK_CHECK(L, 2); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); bool* p_open = 0; bool open = 1; if (lua_isboolean(L, 2)) { open = lua_toboolean(L, 2); p_open = &open; } uint32_t flags = 0; if (lua_isnumber(L, 3)) { flags = luaL_checkint(L, 3); } bool result = ImGui::BeginTabItem(label, p_open, flags); lua_pushboolean(L, result); lua_pushboolean(L, open); return 2; } static int imgui_EndTabItem(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::EndTabItem(); return 0; } // ---------------------------- // ----- WIDGETS --------- // ---------------------------- static int imgui_Text(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); const char* text = luaL_checkstring(L, 1); int wrapped = 0.0f; if(lua_isnumber(L, 2)) wrapped = luaL_checknumber(L, 2); if(wrapped > 0.0f) { ImGui::PushTextWrapPos(wrapped); ImGui::TextWrapped("%s", text); ImGui::PopTextWrapPos(); } else ImGui::Text("%s", text); return 0; } static int imgui_TextGetSize(lua_State* L) { DM_LUA_STACK_CHECK(L, 2); int argc = lua_gettop(L); const char* text = luaL_checkstring(L, 1); float font_size = luaL_checknumber(L, 2); int fontid = 0; float max_width = FLT_MAX; float wrap_width = 0.0f; if(argc > 2) fontid = luaL_checkinteger(L, 3); if(argc > 3) wrap_width = luaL_checknumber(L, 4); ImFont *font = fonts[fontid]; ImVec2 sz = font->CalcTextSizeA(font_size, max_width, wrap_width, text); lua_pushnumber(L, sz.x); lua_pushnumber(L, sz.y); return 2; } static int imgui_TextColored(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); const char* text = luaL_checkstring(L, 1); float r = (float)luaL_checknumber(L, 2); float g = (float)luaL_checknumber(L, 3); float b = (float)luaL_checknumber(L, 4); float a = (float)luaL_checknumber(L, 5); ImVec4 color(r, g, b, a); ImGui::TextColored(color, "%s", text); return 0; } static int imgui_InputText(lua_State* L) { DM_LUA_STACK_CHECK(L, 2); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); const char* text = luaL_checkstring(L, 2); dmStrlCpy(g_imgui_TextBuffer, text, TEXTBUFFER_SIZE); bool changed = ImGui::InputText(label, g_imgui_TextBuffer, TEXTBUFFER_SIZE); lua_pushboolean(L, changed); if (changed) { lua_pushstring(L, g_imgui_TextBuffer); } else { lua_pushnil(L); } return 2; } static int imgui_InputInt(lua_State* L) { DM_LUA_STACK_CHECK(L, 2); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); int value = luaL_checkinteger(L, 2); bool changed = ImGui::InputInt(label, &value); lua_pushboolean(L, changed); if (changed) { lua_pushinteger(L, value); } else { lua_pushnil(L); } return 2; } static int imgui_InputFloat(lua_State* L) { DM_LUA_STACK_CHECK(L, 2); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); float value = luaL_checknumber(L, 2); float step = 0.01f; float step_fast = 1.0f; char float_precision[20] = { "%.6f" }; // check if the third argument is a number if (lua_isnumber(L, 3)) { step = luaL_checknumber(L, 3); // Only accept 4th if we have 3rd param if (lua_isnumber(L, 4)) { step_fast = luaL_checknumber(L, 4); // Only accept 5th if we have 4th param if (lua_isnumber(L, 5)) { int precision_count = lua_tointeger(L, 5); dmSnPrintf(float_precision, sizeof(float_precision), "%%.%df", precision_count ); } } } bool changed = ImGui::InputFloat(label, &value, step, step_fast, float_precision); lua_pushboolean(L, changed); if (changed) { lua_pushnumber(L, value); } else { lua_pushnil(L); } return 2; } static int imgui_InputDouble(lua_State* L) { DM_LUA_STACK_CHECK(L, 2); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); double value = luaL_checknumber(L, 2); double step = 0.01f; double step_fast = 1.0f; char dbl_precision[20] = { "%.6f" }; // check if the third argument is a number if (lua_isnumber(L, 3)) { step = luaL_checknumber(L, 3); // Only accept 4th if we have 3rd param if (lua_isnumber(L, 4)) { step_fast = luaL_checknumber(L, 4); // Only accept 5th if we have 4th param if (lua_isnumber(L, 5)) { int precision_count = lua_tointeger(L, 5); dmSnPrintf(dbl_precision, sizeof(dbl_precision), "%%.%df", precision_count ); } } } bool changed = ImGui::InputDouble(label, &value, step, step_fast, dbl_precision); lua_pushboolean(L, changed); if (changed) { lua_pushnumber(L, value); } else { lua_pushnil(L); } return 2; } static int imgui_InputInt4(lua_State* L) { DM_LUA_STACK_CHECK(L, 5); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); int v[4]; v[0] = luaL_checkinteger(L, 2); v[1] = luaL_checkinteger(L, 3); v[2] = luaL_checkinteger(L, 4); v[3] = luaL_checkinteger(L, 5); bool changed = ImGui::InputInt4(label, v); lua_pushboolean(L, changed); if (changed) { lua_pushnumber(L, v[0]); lua_pushnumber(L, v[1]); lua_pushnumber(L, v[2]); lua_pushnumber(L, v[3]); } else { lua_pushnil(L); lua_pushnil(L); lua_pushnil(L); lua_pushnil(L); } return 5; } static int imgui_InputFloat3(lua_State* L) { DM_LUA_STACK_CHECK(L, 4); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); float v[3]; v[0] = luaL_checknumber(L, 2); v[1] = luaL_checknumber(L, 3); v[2] = luaL_checknumber(L, 4); bool changed = ImGui::InputFloat3(label, v); lua_pushboolean(L, changed); if (changed) { lua_pushnumber(L, v[0]); lua_pushnumber(L, v[1]); lua_pushnumber(L, v[2]); } else { lua_pushnil(L); lua_pushnil(L); lua_pushnil(L); } return 4; } static int imgui_InputFloat4(lua_State* L) { DM_LUA_STACK_CHECK(L, 5); imgui_NewFrame(); const char* label = luaL_checkstring(L, 1); float v[4]; v[0] = luaL_checknumber(L, 2); v[1] = luaL_checknumber(L, 3); v[2] = luaL_checknumber(L, 4); v[3] = luaL_checknumber(L, 5); bool changed = ImGui::InputFloat4(label, v); lua_pushboolean(L, changed); if (changed) { lua_pushnumber(L, v[0]); lua_pushnumber(L, v[1]); lua_pushnumber(L, v[2]); lua_pushnumber(L, v[3]); } else { lua_pushnil(L); lua_pushnil(L); lua_pushnil(L); lua_pushnil(L); } return 5; } static int imgui_Selectable(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); imgui_NewFrame(); const char* text = luaL_checkstring(L, 1); bool selected = lua_toboolean(L, 2); uint32_t flags = 0; if (lua_isnumber(L, 3)) { flags = luaL_checkint(L, 3); } ImGui::Selectable(text, &selected, flags); lua_pushboolean(L, selected); return 1; } static int imgui_Button(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); int argc = lua_gettop(L); imgui_NewFrame(); const char* text = luaL_checkstring(L, 1); bool pushed = false; if(argc > 1) { int width = luaL_checkinteger(L, 2); int height = luaL_checkinteger(L, 3); pushed = ImGui::Button(text, ImVec2(width, height)); } else { pushed = ImGui::Button(text); } lua_pushboolean(L, pushed); return 1; } static int imgui_ButtonImage(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); int argc = lua_gettop(L); imgui_NewFrame(); int tid = luaL_checknumber(L, 1); ImgObject iobj = images[tid]; bool pushed = false; if(argc > 1) { int width = luaL_checkinteger(L, 2); int height = luaL_checkinteger(L, 3); pushed = ImGui::ImageButton((void*)(intptr_t)iobj.tid, ImVec2(width, height)); } else { pushed = ImGui::ImageButton((void*)(intptr_t)iobj.tid, ImVec2(0,0)); } lua_pushboolean(L, pushed); return 1; } static int imgui_Checkbox(lua_State* L) { DM_LUA_STACK_CHECK(L, 2); imgui_NewFrame(); const char* text = luaL_checkstring(L, 1); bool checked = lua_toboolean(L, 2); bool changed = ImGui::Checkbox(text, &checked); lua_pushboolean(L, changed); lua_pushboolean(L, checked); return 2; } // ---------------------------- // ----- LAYOUT --------- // ---------------------------- static int imgui_SameLine(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); float offset = 0.0f; if (lua_isnumber(L, 1)) { offset = lua_tonumber(L, 1); } ImGui::SameLine(offset); return 0; } static int imgui_NewLine(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::NewLine(); return 0; } static int imgui_Bullet(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::Bullet(); return 0; } static int imgui_Indent(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::Indent(); return 0; } static int imgui_Unindent(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::Unindent(); return 0; } static int imgui_Spacing(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::Spacing(); return 0; } static int imgui_Separator(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); ImGui::Separator(); return 0; } // ---------------------------- // ----- IMGUI PLOT ----------- // ---------------------------- static float values_lines[MAX_HISTOGRAM_VALUES]; static int imgui_PlotLines(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); const char *lbl = luaL_checkstring(L, 1); int valoff = luaL_checkinteger(L, 2); int width = luaL_checkinteger(L, 3); int height = luaL_checkinteger(L, 4); luaL_checktype(L, 5, LUA_TTABLE); // Table is at idx 5 lua_pushnil(L); int valct = 0; // Build a number array matching the buffer. They are all assumed to be type float (for the time being) while(( lua_next( L, 5 ) != 0) && (valct < MAX_HISTOGRAM_VALUES)) { values_lines[valct++] = (float)lua_tonumber( L, -1 ); lua_pop( L, 1 ); } imgui_NewFrame(); ImVec2 gsize(width, height); ImGui::PlotLines(lbl, values_lines, valct, valoff, NULL, FLT_MAX, FLT_MAX, gsize); return 0; } // Keep a label mapped histograms. This minimised alloc and realloc of value mem static float values_hist[MAX_HISTOGRAM_VALUES]; static int imgui_PlotHistogram(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); const char *lbl = luaL_checkstring(L, 1); int valoff = luaL_checkinteger(L, 2); int width = luaL_checkinteger(L, 3); int height = luaL_checkinteger(L, 4); luaL_checktype(L, 5, LUA_TTABLE); // Table is at idx 5 lua_pushnil(L); int valct = 0; // Build a number array matching the buffer. They are all assumed to be type float (for the time being) while(( lua_next( L, 5 ) != 0) && (valct < MAX_HISTOGRAM_VALUES)) { values_hist[valct++] = (float)lua_tonumber( L, -1 ); lua_pop( L, 1 ); } imgui_NewFrame(); ImVec2 gsize(width, height); ImGui::PlotHistogram(lbl, values_hist, valct, valoff, NULL, FLT_MAX, FLT_MAX, gsize); return 0; } // ---------------------------- // ----- IMGUI DEMO ----------- // ---------------------------- static int imgui_Demo(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); bool show_demo_window = true; ImGui::ShowDemoWindow(&show_demo_window); return 0; } // ---------------------------- // ----- INPUT ---------------- // ---------------------------- static int imgui_IsMouseDoubleClicked(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); imgui_NewFrame(); uint32_t button = luaL_checknumber(L, 1); ImGui::IsMouseDoubleClicked(button); return 0; } static int imgui_IsMouseClicked(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); imgui_NewFrame(); uint32_t button = luaL_checknumber(L, 1); bool clicked = ImGui::IsMouseClicked(button); lua_pushboolean(L, clicked); return 1; } static int imgui_IsItemClicked(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); imgui_NewFrame(); uint32_t button = luaL_checknumber(L, 1); bool clicked = ImGui::IsItemClicked(button); lua_pushboolean(L, clicked); return 1; } static int imgui_IsItemHovered(lua_State* L) { DM_LUA_STACK_CHECK(L, 1); imgui_NewFrame(); bool hovered = ImGui::IsItemHovered(); lua_pushboolean(L, hovered); return 1; } // ---------------------------- // ----- STYLE ---------------- // ---------------------------- static int imgui_SetStyleWindowBorderSize(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiStyle& style = ImGui::GetStyle(); style.WindowBorderSize = luaL_checknumber(L, 1); return 0; } static int imgui_SetStyleChildBorderSize(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiStyle& style = ImGui::GetStyle(); style.ChildBorderSize = luaL_checknumber(L, 1); return 0; } static int imgui_SetStyleWindowRounding(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiStyle& style = ImGui::GetStyle(); style.WindowRounding = luaL_checknumber(L, 1); return 0; } static int imgui_SetStyleFrameRounding(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiStyle& style = ImGui::GetStyle(); style.FrameRounding = luaL_checknumber(L, 1); return 0; } static int imgui_SetStyleTabRounding(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiStyle& style = ImGui::GetStyle(); style.TabRounding = luaL_checknumber(L, 1); return 0; } static int imgui_SetStyleScrollbarRounding(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiStyle& style = ImGui::GetStyle(); style.ScrollbarRounding = luaL_checknumber(L, 1); return 0; } static int imgui_SetStyleColor(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiStyle& style = ImGui::GetStyle(); double r = luaL_checknumber(L, 2); double g = luaL_checknumber(L, 3); double b = luaL_checknumber(L, 4); double a = luaL_checknumber(L, 5); style.Colors[luaL_checkinteger(L, 1)] = ImVec4(r, g, b, a); return 0; } static int imgui_SetWindowFontScale(lua_State *L) { DM_LUA_STACK_CHECK(L, 0); float scale = luaL_checknumber(L, 1); ImGui::SetWindowFontScale(scale); return 0; } static int imgui_SetCursorPos(lua_State *L) { DM_LUA_STACK_CHECK(L, 0); int posx = luaL_checkinteger(L, 1); int posy = luaL_checkinteger(L, 2); ImVec2 pos(posx, posy); ImGui::SetCursorPos(pos); return 0; } // ---------------------------- // ----- CONFIG ----------------- // ---------------------------- static int imgui_SetDefaults(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); ImGuiIO& io = ImGui::GetIO(); ImFont * def = io.Fonts->AddFontDefault(); fonts.push_back(def); return 0; } static int imgui_SetIniFilename(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); const char *filename = 0; if (lua_isstring(L, 1)) { filename = luaL_checkstring(L, 1); } ImGui::GetIO().IniFilename = filename; return 0; } static int imgui_FontAddTTFFile(lua_State * L) { DM_LUA_STACK_CHECK(L, 1); const char * ttf_filename = luaL_checkstring(L, 1); float font_size = luaL_checknumber(L, 2); ImGuiIO& io = ImGui::GetIO(); ImFont* font = io.Fonts->AddFontFromFileTTF(ttf_filename, font_size); // Put font in map. if(font != NULL) { fonts.push_back(font); lua_pushinteger(L, fonts.size() - 1); } else { lua_pushnil(L); } return 1; } static int imgui_FontAddTTFData(lua_State * L) { DM_LUA_STACK_CHECK(L, 1); const char * ttf_data = luaL_checkstring(L, 1); int ttf_data_size = luaL_checknumber(L, 2); float font_size = luaL_checknumber(L, 3); int font_pixels = luaL_checknumber(L, 4); char *ttf_data_cpy = (char *)calloc(ttf_data_size, sizeof(char)); memcpy(ttf_data_cpy, ttf_data, ttf_data_size); ImGuiIO& io = ImGui::GetIO(); ImFont* font = io.Fonts->AddFontFromMemoryTTF((void *)ttf_data_cpy, font_size, font_pixels); // Put font in map. if(font != NULL) { fonts.push_back(font); lua_pushinteger(L, fonts.size() - 1); } else { lua_pushnil(L); } return 1; } static int imgui_FontPush(lua_State *L) { DM_LUA_STACK_CHECK(L, 0); int fontid = luaL_checkinteger(L, 1); if(fontid >= 0 && fontid < fonts.size()) ImGui::PushFont(fonts[fontid]); return 0; } static int imgui_FontPop(lua_State *L) { DM_LUA_STACK_CHECK(L, 0); ImGui::PopFont(); return 0; } static int imgui_FontScale(lua_State *L) { DM_LUA_STACK_CHECK(L, 1); float oldscale = 1.0f; int fontid = luaL_checkinteger(L, 1); float fontscale = luaL_checknumber(L, 2); if(fontid >= 0 && fontid < fonts.size()) oldscale = fonts[fontid]->Scale; fonts[fontid]->Scale = fontscale; lua_pushnumber(L, oldscale); return 1; } // ---------------------------- // ----- DRAW ----------------- // ---------------------------- static dmExtension::Result imgui_Draw(dmExtension::Params* params) { imgui_NewFrame(); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); g_imgui_NewFrame = false; return dmExtension::RESULT_OK; } static int imgui_DrawLine(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); int x1 = luaL_checkinteger(L, 1); int y1 = luaL_checkinteger(L, 2); int x2 = luaL_checkinteger(L, 3); int y2 = luaL_checkinteger(L, 4); unsigned int col = (unsigned int)luaL_checkinteger(L, 5); ImDrawList *dl = ImGui::GetWindowDrawList(); ImVec2 p1(x1, y1); ImVec2 p2(x2, y2); dl->AddLine(p1, p2, col); return 0; } static int imgui_DrawRect(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); int x = luaL_checkinteger(L, 1); int y = luaL_checkinteger(L, 2); int w = luaL_checkinteger(L, 3); int h = luaL_checkinteger(L, 4); unsigned int col = (unsigned int)luaL_checkinteger(L, 5); ImDrawList *dl = ImGui::GetWindowDrawList(); ImVec2 minv(x, y); ImVec2 maxv(x + w, y + h); dl->AddRect(minv, maxv, col); return 0; } static int imgui_DrawRectFilled(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); int x = luaL_checkinteger(L, 1); int y = luaL_checkinteger(L, 2); int w = luaL_checkinteger(L, 3); int h = luaL_checkinteger(L, 4); unsigned int col = (unsigned int)luaL_checkinteger(L, 5); ImDrawList *dl = ImGui::GetWindowDrawList(); ImVec2 minv(x, y); ImVec2 maxv(x + w, y + h); dl->AddRectFilled(minv, maxv, col); return 0; } static int imgui_DrawProgressBar(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); float progress = luaL_checknumber(L, 1); float xsize = luaL_checknumber(L, 2); float ysize = luaL_checknumber(L, 3); ImVec2 size_param(xsize, ysize); ImGui::ProgressBar(progress, size_param); return 0; } // ---------------------------- // ----- IMGUI INIT/SHUTDOWN -- // ---------------------------- static void imgui_Init(float width, float height) { #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) int r = gl3wInit(); if (r != GL3W_OK) { dmLogError("Failed to initialize OpenGL: %d", r); } #endif IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(width, height); // init keymap list // We will be sending the correct ImGuiKey_ enums from Lua for (int i = 0; i < ImGuiKey_COUNT; i++) { io.KeyMap[i] = i; } ImGui_ImplOpenGL3_Init(); } static void imgui_Shutdown() { dmLogInfo("imgui_Shutdown"); fonts.clear(); images.clear(); ImGui_ImplOpenGL3_Shutdown(); ImGui::DestroyContext(); } static void imgui_ExtensionInit() { dmExtension::RegisterCallback(dmExtension::CALLBACK_POST_RENDER, imgui_Draw ); if (g_imgui_TextBuffer) { free(g_imgui_TextBuffer); } g_imgui_TextBuffer = (char*)malloc(TEXTBUFFER_SIZE); } static void imgui_ExtensionShutdown() { if (g_imgui_TextBuffer) { free(g_imgui_TextBuffer); g_imgui_TextBuffer = 0; } } // Functions exposed to Lua static const luaL_reg Module_methods[] = { {"image_load", imgui_ImageLoad}, {"image_load_data", imgui_ImageLoadData}, {"image_get", imgui_ImageGet}, {"image_free", imgui_ImageFree}, {"image_add", imgui_ImageAdd}, {"image_b64_decode", imgui_ImageB64Decode}, {"font_add_ttf_file", imgui_FontAddTTFFile}, {"font_add_ttf_data", imgui_FontAddTTFData}, {"font_push", imgui_FontPush}, {"font_pop", imgui_FontPop}, {"font_scale", imgui_FontScale}, {"set_next_window_size", imgui_SetNextWindowSize}, {"set_next_window_pos", imgui_SetNextWindowPos}, {"begin_window", imgui_Begin}, {"end_window", imgui_End}, {"is_window_focused", imgui_IsWindowFocused}, {"begin_child", imgui_BeginChild}, {"end_child", imgui_EndChild}, {"begin_tab_bar", imgui_BeginTabBar}, {"end_tab_bar", imgui_EndTabBar}, {"begin_tab_item", imgui_BeginTabItem}, {"end_tab_item", imgui_EndTabItem}, {"begin_combo", imgui_BeginCombo}, {"end_combo", imgui_EndCombo}, {"combo", imgui_Combo}, {"begin_table", imgui_BeginTable}, {"end_table", imgui_EndTable}, {"table_next_row", imgui_TableNextRow}, {"table_next_column", imgui_TableNextColumn}, {"table_set_column_index", imgui_TableSetColumnIndex}, {"table_setup_column", imgui_TableSetupColumn}, {"table_headers_row", imgui_TableHeadersRow}, {"tree_node", imgui_TreeNode}, {"tree_pop", imgui_TreePop}, {"selectable", imgui_Selectable}, {"text", imgui_Text}, {"text_colored", imgui_TextColored}, {"input_text", imgui_InputText}, {"input_int", imgui_InputInt}, {"input_int4", imgui_InputInt4}, {"input_float", imgui_InputFloat}, {"input_double", imgui_InputDouble}, {"input_float3", imgui_InputFloat3}, {"input_float4", imgui_InputFloat4}, {"button", imgui_Button}, {"button_image", imgui_ButtonImage}, {"checkbox", imgui_Checkbox}, {"same_line", imgui_SameLine}, {"new_line", imgui_NewLine}, {"bullet", imgui_Bullet}, {"indent", imgui_Indent}, {"unindent", imgui_Unindent}, {"spacing", imgui_Spacing}, {"separator", imgui_Separator}, {"plot_lines", imgui_PlotLines}, {"plot_histogram", imgui_PlotHistogram}, {"text_getsize", imgui_TextGetSize}, {"draw_rect", imgui_DrawRect}, {"draw_rect_filled", imgui_DrawRectFilled}, {"draw_line", imgui_DrawLine}, {"draw_progress", imgui_DrawProgressBar}, {"demo", imgui_Demo}, {"set_mouse_input", imgui_SetMouseInput}, {"set_key_down", imgui_SetKeyDown}, {"set_key_modifier_ctrl", imgui_SetKeyModifierCtrl}, {"set_key_modifier_shift", imgui_SetKeyModifierShift}, {"set_key_modifier_alt", imgui_SetKeyModifierAlt}, {"set_key_modifier_super", imgui_SetKeyModifierSuper}, {"add_input_character", imgui_AddInputCharacter}, {"is_item_clicked", imgui_IsItemClicked}, {"is_item_hovered", imgui_IsItemHovered}, {"is_mouse_clicked", imgui_IsMouseClicked}, {"is_mouse_double_clicked", imgui_IsMouseDoubleClicked}, {"set_style_window_rounding", imgui_SetStyleWindowRounding}, {"set_style_window_bordersize", imgui_SetStyleWindowBorderSize}, {"set_style_child_bordersize", imgui_SetStyleChildBorderSize}, {"set_style_frame_rounding", imgui_SetStyleFrameRounding}, {"set_style_tab_rounding", imgui_SetStyleTabRounding}, {"set_style_scrollbar_rounding", imgui_SetStyleScrollbarRounding}, {"set_style_color", imgui_SetStyleColor}, {"set_defaults", imgui_SetDefaults}, {"set_ini_filename", imgui_SetIniFilename}, {"set_cursor_pos", imgui_SetCursorPos}, {"set_display_size", imgui_SetDisplaySize}, {"set_window_font_scale", imgui_SetWindowFontScale}, {0, 0} }; static void lua_setfieldstringstring(lua_State* L, const char* key, const char* value) { int top = lua_gettop(L); lua_pushstring(L, value); lua_setfield(L, -2, key); assert(top == lua_gettop(L)); } static void lua_setfieldstringint(lua_State* L, const char* key, uint32_t value) { int top = lua_gettop(L); lua_pushnumber(L, value); lua_setfield(L, -2, key); assert(top == lua_gettop(L)); } static void LuaInit(lua_State* L) { int top = lua_gettop(L); // Register lua names luaL_register(L, MODULE_NAME, Module_methods); lua_setfieldstringint(L, "MOUSEBUTTON_LEFT", ImGuiMouseButton_Left); lua_setfieldstringint(L, "MOUSEBUTTON_RIGHT", ImGuiMouseButton_Right); lua_setfieldstringint(L, "MOUSEBUTTON_MIDDLE", ImGuiMouseButton_Middle); lua_setfieldstringint(L, "SELECTABLE_DONT_CLOSE_POPUPS", ImGuiSelectableFlags_DontClosePopups); lua_setfieldstringint(L, "SELECTABLE_SPAN_ALL_COLUMNS", ImGuiSelectableFlags_SpanAllColumns); lua_setfieldstringint(L, "SELECTABLE_ALLOW_DOUBLE_CLICK", ImGuiSelectableFlags_AllowDoubleClick); lua_setfieldstringint(L, "SELECTABLE_DISABLED", ImGuiSelectableFlags_Disabled); lua_setfieldstringint(L, "SELECTABLE_ALLOW_ITEM_OVERLAP", ImGuiSelectableFlags_AllowItemOverlap); lua_setfieldstringint(L, "TABITEM_UNSAVED_DOCUMENT", ImGuiTabItemFlags_UnsavedDocument); lua_setfieldstringint(L, "TABITEM_SET_SELECTED", ImGuiTabItemFlags_SetSelected); lua_setfieldstringint(L, "TABITEM_NO_CLOSE_WITH_MIDDLE_MOUSE_BUTTON", ImGuiTabItemFlags_NoCloseWithMiddleMouseButton); lua_setfieldstringint(L, "TABITEM_NO_PUSH_ID", ImGuiTabItemFlags_NoPushId); lua_setfieldstringint(L, "TABITEM_NO_TOOLTIP", ImGuiTabItemFlags_NoTooltip); lua_setfieldstringint(L, "TABITEM_NO_REORDER", ImGuiTabItemFlags_NoReorder); lua_setfieldstringint(L, "TABITEM_LEADING", ImGuiTabItemFlags_Leading); lua_setfieldstringint(L, "TABITEM_TRAILING", ImGuiTabItemFlags_Trailing); lua_setfieldstringint(L, "FOCUSED_CHILD_WINDOWS", ImGuiFocusedFlags_ChildWindows); lua_setfieldstringint(L, "FOCUSED_ROOT_WINDOW", ImGuiFocusedFlags_RootWindow); lua_setfieldstringint(L, "FOCUSED_ANY_WINDOW", ImGuiFocusedFlags_AnyWindow); lua_setfieldstringint(L, "FOCUSED_ROOT_AND_CHILD_WINDOWS", ImGuiFocusedFlags_RootAndChildWindows); lua_setfieldstringint(L, "TREENODE_SELECTED", ImGuiTreeNodeFlags_Selected); lua_setfieldstringint(L, "TREENODE_FRAMED", ImGuiTreeNodeFlags_Framed); lua_setfieldstringint(L, "TREENODE_ALLOW_ITEM_OVERLAP", ImGuiTreeNodeFlags_AllowItemOverlap); lua_setfieldstringint(L, "TREENODE_NO_TREE_PUSH_ON_OPEN", ImGuiTreeNodeFlags_NoTreePushOnOpen); lua_setfieldstringint(L, "TREENODE_NO_AUTO_OPEN_ON_LOG", ImGuiTreeNodeFlags_NoAutoOpenOnLog); lua_setfieldstringint(L, "TREENODE_DEFAULT_OPEN", ImGuiTreeNodeFlags_DefaultOpen); lua_setfieldstringint(L, "TREENODE_OPEN_ON_DOUBLE_CLICK", ImGuiTreeNodeFlags_OpenOnDoubleClick); lua_setfieldstringint(L, "TREENODE_OPEN_ON_ARROW", ImGuiTreeNodeFlags_OpenOnArrow); lua_setfieldstringint(L, "TREENODE_LEAF", ImGuiTreeNodeFlags_Leaf); lua_setfieldstringint(L, "TREENODE_BULLET", ImGuiTreeNodeFlags_Bullet); lua_setfieldstringint(L, "TREENODE_FRAME_PADDING", ImGuiTreeNodeFlags_FramePadding); lua_setfieldstringint(L, "TREENODE_SPAN_AVAILABLE_WIDTH", ImGuiTreeNodeFlags_SpanAvailWidth); lua_setfieldstringint(L, "TREENODE_SPAN_FULL_WIDTH", ImGuiTreeNodeFlags_SpanFullWidth); lua_setfieldstringint(L, "TREENODE_NAV_LEFT_JUMPS_BACK_HERE", ImGuiTreeNodeFlags_NavLeftJumpsBackHere); lua_setfieldstringint(L, "ImGuiCol_Text", ImGuiCol_Text); lua_setfieldstringint(L, "ImGuiCol_TextDisabled", ImGuiCol_TextDisabled); lua_setfieldstringint(L, "ImGuiCol_WindowBg", ImGuiCol_WindowBg); lua_setfieldstringint(L, "ImGuiCol_ChildBg", ImGuiCol_ChildBg); lua_setfieldstringint(L, "ImGuiCol_PopupBg", ImGuiCol_PopupBg); lua_setfieldstringint(L, "ImGuiCol_Border", ImGuiCol_Border); lua_setfieldstringint(L, "ImGuiCol_BorderShadow", ImGuiCol_BorderShadow); lua_setfieldstringint(L, "ImGuiCol_FrameBg", ImGuiCol_FrameBg); lua_setfieldstringint(L, "ImGuiCol_FrameBgHovered", ImGuiCol_FrameBgHovered); lua_setfieldstringint(L, "ImGuiCol_FrameBgActive", ImGuiCol_FrameBgActive); lua_setfieldstringint(L, "ImGuiCol_TitleBg", ImGuiCol_TitleBg); lua_setfieldstringint(L, "ImGuiCol_TitleBgActive", ImGuiCol_TitleBgActive); lua_setfieldstringint(L, "ImGuiCol_TitleBgCollapsed", ImGuiCol_TitleBgCollapsed); lua_setfieldstringint(L, "ImGuiCol_MenuBarBg", ImGuiCol_MenuBarBg); lua_setfieldstringint(L, "ImGuiCol_ScrollbarBg", ImGuiCol_ScrollbarBg); lua_setfieldstringint(L, "ImGuiCol_ScrollbarGrab", ImGuiCol_ScrollbarGrab); lua_setfieldstringint(L, "ImGuiCol_ScrollbarGrabHovered", ImGuiCol_ScrollbarGrabHovered); lua_setfieldstringint(L, "ImGuiCol_ScrollbarGrabActive", ImGuiCol_ScrollbarGrabActive); lua_setfieldstringint(L, "ImGuiCol_CheckMark", ImGuiCol_CheckMark); lua_setfieldstringint(L, "ImGuiCol_SliderGrab", ImGuiCol_SliderGrab); lua_setfieldstringint(L, "ImGuiCol_SliderGrabActive", ImGuiCol_SliderGrabActive); lua_setfieldstringint(L, "ImGuiCol_Button", ImGuiCol_Button); lua_setfieldstringint(L, "ImGuiCol_ButtonHovered", ImGuiCol_ButtonHovered); lua_setfieldstringint(L, "ImGuiCol_ButtonActive", ImGuiCol_ButtonActive); lua_setfieldstringint(L, "ImGuiCol_Header", ImGuiCol_Header); lua_setfieldstringint(L, "ImGuiCol_HeaderHovered", ImGuiCol_HeaderHovered); lua_setfieldstringint(L, "ImGuiCol_HeaderActive", ImGuiCol_HeaderActive); lua_setfieldstringint(L, "ImGuiCol_Separator", ImGuiCol_Separator); lua_setfieldstringint(L, "ImGuiCol_SeparatorHovered", ImGuiCol_SeparatorHovered); lua_setfieldstringint(L, "ImGuiCol_SeparatorActive", ImGuiCol_SeparatorActive); lua_setfieldstringint(L, "ImGuiCol_ResizeGrip", ImGuiCol_ResizeGrip); lua_setfieldstringint(L, "ImGuiCol_ResizeGripHovered", ImGuiCol_ResizeGripHovered); lua_setfieldstringint(L, "ImGuiCol_ResizeGripActive", ImGuiCol_ResizeGripActive); lua_setfieldstringint(L, "ImGuiCol_Tab", ImGuiCol_Tab); lua_setfieldstringint(L, "ImGuiCol_TabHovered", ImGuiCol_TabHovered); lua_setfieldstringint(L, "ImGuiCol_TabActive", ImGuiCol_TabActive); lua_setfieldstringint(L, "ImGuiCol_TabUnfocused", ImGuiCol_TabUnfocused); lua_setfieldstringint(L, "ImGuiCol_TabUnfocusedActive", ImGuiCol_TabUnfocusedActive); lua_setfieldstringint(L, "ImGuiCol_PlotLines", ImGuiCol_PlotLines); lua_setfieldstringint(L, "ImGuiCol_PlotLinesHovered", ImGuiCol_PlotLinesHovered); lua_setfieldstringint(L, "ImGuiCol_PlotHistogram", ImGuiCol_PlotHistogram); lua_setfieldstringint(L, "ImGuiCol_PlotHistogramHovered", ImGuiCol_PlotHistogramHovered); lua_setfieldstringint(L, "ImGuiCol_TableHeaderBg", ImGuiCol_TableHeaderBg); lua_setfieldstringint(L, "ImGuiCol_TableBorderStrong", ImGuiCol_TableBorderStrong); lua_setfieldstringint(L, "ImGuiCol_TableBorderLight", ImGuiCol_TableBorderLight); lua_setfieldstringint(L, "ImGuiCol_TableRowBg", ImGuiCol_TableRowBg); lua_setfieldstringint(L, "ImGuiCol_TableRowBgAlt", ImGuiCol_TableRowBgAlt); lua_setfieldstringint(L, "ImGuiCol_TextSelectedBg", ImGuiCol_TextSelectedBg); lua_setfieldstringint(L, "ImGuiCol_DragDropTarget", ImGuiCol_DragDropTarget); lua_setfieldstringint(L, "ImGuiCol_NavHighlight", ImGuiCol_NavHighlight); lua_setfieldstringint(L, "ImGuiCol_NavWindowingHighlight", ImGuiCol_NavWindowingHighlight); lua_setfieldstringint(L, "ImGuiCol_NavWindowingDimBg", ImGuiCol_NavWindowingDimBg); lua_setfieldstringint(L, "ImGuiCol_ModalWindowDimBg", ImGuiCol_ModalWindowDimBg); lua_setfieldstringint(L, "TABLECOLUMN_NONE", ImGuiTableColumnFlags_None); lua_setfieldstringint(L, "TABLECOLUMN_DEFAULTHIDE", ImGuiTableColumnFlags_DefaultHide); // Default as a hidden/disabled column. lua_setfieldstringint(L, "TABLECOLUMN_DEFAULTSORT", ImGuiTableColumnFlags_DefaultSort); // Default as a sorting column. lua_setfieldstringint(L, "TABLECOLUMN_WIDTHSTRETCH", ImGuiTableColumnFlags_WidthStretch); // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). lua_setfieldstringint(L, "TABLECOLUMN_WIDTHFIXED", ImGuiTableColumnFlags_WidthFixed); // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). lua_setfieldstringint(L, "TABLECOLUMN_NORESIZE", ImGuiTableColumnFlags_NoResize); // Disable manual resizing. lua_setfieldstringint(L, "TABLECOLUMN_NOREORDER", ImGuiTableColumnFlags_NoReorder); // Disable manual reordering this column, this will also prevent other columns from crossing over this column. lua_setfieldstringint(L, "TABLECOLUMN_NOHIDE", ImGuiTableColumnFlags_NoHide); // Disable ability to hide/disable this column. lua_setfieldstringint(L, "TABLECOLUMN_NOCLIP", ImGuiTableColumnFlags_NoClip); // Disable clipping for this column (all NoClip columns will render in a same draw command). lua_setfieldstringint(L, "TABLECOLUMN_NOSORT", ImGuiTableColumnFlags_NoSort); // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). lua_setfieldstringint(L, "TABLECOLUMN_NOSORTASCENDING", ImGuiTableColumnFlags_NoSortAscending); // Disable ability to sort in the ascending direction. lua_setfieldstringint(L, "TABLECOLUMN_NOSORTDESCENDING", ImGuiTableColumnFlags_NoSortDescending); // Disable ability to sort in the descending direction. lua_setfieldstringint(L, "TABLECOLUMN_NOHEADERWIDTH", ImGuiTableColumnFlags_NoHeaderWidth); // Disable header text width contribution to automatic column width. lua_setfieldstringint(L, "TABLECOLUMN_PREFERSORTASCENDING", ImGuiTableColumnFlags_PreferSortAscending); // Make the initial sort direction Ascending when first sorting on this column (default). lua_setfieldstringint(L, "TABLECOLUMN_PREFERSORTDESCENDING", ImGuiTableColumnFlags_PreferSortDescending); // Make the initial sort direction Descending when first sorting on this column. lua_setfieldstringint(L, "TABLECOLUMN_INDENTENABLE", ImGuiTableColumnFlags_IndentEnable); // Use current Indent value when entering cell (default for column 0). lua_setfieldstringint(L, "TABLECOLUMN_INDENTDISABLE", ImGuiTableColumnFlags_IndentDisable); // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. lua_setfieldstringint(L, "WINDOWFLAGS_NONE", ImGuiWindowFlags_None); lua_setfieldstringint(L, "WINDOWFLAGS_NOTITLEBAR", ImGuiWindowFlags_NoTitleBar); // Disable title-bar lua_setfieldstringint(L, "WINDOWFLAGS_NORESIZE", ImGuiWindowFlags_NoResize); // Disable user resizing with the lower-right grip lua_setfieldstringint(L, "WINDOWFLAGS_NOMOVE", ImGuiWindowFlags_NoMove); // Disable user moving the window lua_setfieldstringint(L, "WINDOWFLAGS_NOSCROLLBAR", ImGuiWindowFlags_NoScrollbar); // Disable scrollbars (window can still scroll with mouse or programmatically) lua_setfieldstringint(L, "WINDOWFLAGS_NOSCROLLWITHMOUSE", ImGuiWindowFlags_NoScrollWithMouse); // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. lua_setfieldstringint(L, "WINDOWFLAGS_NOCOLLAPSE", ImGuiWindowFlags_NoCollapse); // Disable user collapsing window by double-clicking on it lua_setfieldstringint(L, "WINDOWFLAGS_ALWAYSAUTORESIZE", ImGuiWindowFlags_AlwaysAutoResize); // Resize every window to its content every frame lua_setfieldstringint(L, "WINDOWFLAGS_NOBACKGROUND", ImGuiWindowFlags_NoBackground); // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). lua_setfieldstringint(L, "WINDOWFLAGS_NOSAVEDSETTINGS", ImGuiWindowFlags_NoSavedSettings); // Never load/save settings in .ini file lua_setfieldstringint(L, "WINDOWFLAGS_NOMOUSEINPUTS", ImGuiWindowFlags_NoMouseInputs); // Disable catching mouse, hovering test with pass through. lua_setfieldstringint(L, "WINDOWFLAGS_MENUBAR", ImGuiWindowFlags_MenuBar); // Has a menu-bar lua_setfieldstringint(L, "WINDOWFLAGS_HORIZONTALSCROLLBAR", ImGuiWindowFlags_HorizontalScrollbar); // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. lua_setfieldstringint(L, "WINDOWFLAGS_NOFOCUSONAPPEARING", ImGuiWindowFlags_NoFocusOnAppearing); // Disable taking focus when transitioning from hidden to visible state lua_setfieldstringint(L, "WINDOWFLAGS_NOBRINGTOFRONTONFOCUS", ImGuiWindowFlags_NoBringToFrontOnFocus); // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) lua_setfieldstringint(L, "WINDOWFLAGS_ALWAYSVERTICALSCROLLBAR", ImGuiWindowFlags_AlwaysVerticalScrollbar); // Always show vertical scrollbar (even if ContentSize.y < Size.y) lua_setfieldstringint(L, "WINDOWFLAGS_ALWAYSHORIZONTALSCROLLBAR", ImGuiWindowFlags_AlwaysHorizontalScrollbar); // Always show horizontal scrollbar (even if ContentSize.x < Size.x) lua_setfieldstringint(L, "WINDOWFLAGS_ALWAYSUSEWINDOWPADDING", ImGuiWindowFlags_AlwaysUseWindowPadding); // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) lua_setfieldstringint(L, "WINDOWFLAGS_NONAVINPUTS", ImGuiWindowFlags_NoNavInputs); // No gamepad/keyboard navigation within the window lua_setfieldstringint(L, "WINDOWFLAGS_NONAVFOCUS", ImGuiWindowFlags_NoNavFocus); // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB) lua_setfieldstringint(L, "WINDOWFLAGS_UNSAVEDDOCUMENT", ImGuiWindowFlags_UnsavedDocument); // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. When used in a tab/docking context, tab is selected on closure and closure is deferred by one frame to allow code to cancel the closure (with a confirmation popup, etc.) without flicker. lua_setfieldstringint(L, "WINDOWFLAGS_NONAV", ImGuiWindowFlags_NoNav); // ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, lua_setfieldstringint(L, "WINDOWFLAGS_NODECORATION", ImGuiWindowFlags_NoDecoration); // ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, lua_setfieldstringint(L, "WINDOWFLAGS_NOINPUTS", ImGuiWindowFlags_NoInputs); // ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, lua_pop(L, 1); assert(top == lua_gettop(L)); } dmExtension::Result AppInitializeDefoldImGui(dmExtension::AppParams* params) { imgui_ExtensionInit(); return dmExtension::RESULT_OK; } dmExtension::Result InitializeDefoldImGui(dmExtension::Params* params) { LuaInit(params->m_L); float displayWidth = dmConfigFile::GetFloat(params->m_ConfigFile, "display.width", 960.0f); float displayHeight = dmConfigFile::GetFloat(params->m_ConfigFile, "display.height", 540.0f); imgui_Init(displayWidth, displayHeight); return dmExtension::RESULT_OK; } dmExtension::Result AppFinalizeDefoldImGui(dmExtension::AppParams* params) { return dmExtension::RESULT_OK; } dmExtension::Result FinalizeDefoldImGui(dmExtension::Params* params) { dmLogInfo("FinalizeDefoldImGui"); imgui_Shutdown(); imgui_ExtensionShutdown(); return dmExtension::RESULT_OK; } dmExtension::Result OnUpdateDefoldImGui(dmExtension::Params* params) { return dmExtension::RESULT_OK; } void OnEventDefoldImGui(dmExtension::Params* params, const dmExtension::Event* event) { switch(event->m_Event) { case dmExtension::EVENT_ID_ACTIVATEAPP: //dmLogInfo("OnEventDefoldImGui - EVENT_ID_ACTIVATEAPP\n"); break; case dmExtension::EVENT_ID_DEACTIVATEAPP: //dmLogInfo("OnEventDefoldImGui - EVENT_ID_DEACTIVATEAPP\n"); break; case dmExtension::EVENT_ID_ICONIFYAPP: //dmLogInfo("OnEventDefoldImGui - EVENT_ID_ICONIFYAPP\n"); break; case dmExtension::EVENT_ID_DEICONIFYAPP: //dmLogInfo("OnEventDefoldImGui - EVENT_ID_DEICONIFYAPP\n"); break; default: //dmLogWarning("OnEventDefoldImGui - Unknown event id\n"); break; } } DM_DECLARE_EXTENSION(DefoldImGui, LIB_NAME, AppInitializeDefoldImGui, AppFinalizeDefoldImGui, InitializeDefoldImGui, OnUpdateDefoldImGui, OnEventDefoldImGui, FinalizeDefoldImGui)
#include once <printi16.asm>
#include "ScoreBroad.h" ScoreBroad* ScoreBroad::createScoreBroad(int score, int width, int height, const char* title, int typt, float x, float y) { ScoreBroad* enemy = new ScoreBroad(); if (enemy&&enemy->init()) { enemy->autorelease(); enemy->enemyInit(score, width, height, title, typt, x, y); return enemy; } CC_SAFE_DELETE(enemy); return NULL; } bool ScoreBroad::init() { if (!Label::init()) { return false; } return true; } void ScoreBroad::enemyInit(int score, int width, int height, const char* title, int typt, float x, float y) { this->type = typt; this->score = score; if (typt == 1) { background = LayerColor::create(Color4B(2, 168, 209, 255), width, height); background->setPosition(x, y); addChild(background); scoreLabel = Label::create(String::createWithFormat("%d", score)->getCString(), "Arail.ttf", 40); scoreLabel->setPosition(width / 2, height / 2); background->addChild(scoreLabel); } else { background = LayerColor::create(Color4B(215, 224, 223, 255), width, height); background->setPosition(x, y); addChild(background); auto* label = Label::create(title, "Arail.ttf", 26); label->setPosition(width / 2, height - 20); background->addChild(label); scoreLabel = Label::create(String::createWithFormat("%d", score)->getCString(), "Arail.ttf", 34); scoreLabel->setPosition(width / 2, 30); background->addChild(scoreLabel); } } void ScoreBroad::setScore(int number) { this->score = number; scoreLabel->setString(String::createWithFormat("%d", number)->getCString()); } int ScoreBroad::getScore() { return this->score; }
; Sonic the Hedgehog 2 disassembled Z80 sound driver ; Disassembled by Xenowhirl for AS ; Additional disassembly work by RAS Oct 2008 ; RAS' work merged into SVN by Flamewing ; --------------------------------------------------------------------------- FixDriverBugs = 0 OptimiseDriver = 0 ; --------------------------------------------------------------------------- ; NOTES: ; ; Set your editor's tab width to 8 characters wide for viewing this file. ; ; This code is compressed in the ROM, but you can edit it here as uncompressed ; and it will automatically be assembled and compressed into the correct place ; during the build process. ; ; This Z80 code can use labels and equates defined in the 68k code, ; and the 68k code can use the labels and equates defined in here. ; This is fortunate, as they contain references to each other's addresses. ; ; If you want to add significant amounts of extra code to this driver, ; I suggest putting your code as far down as possible, after the function zloc_12FC. ; That will make you less likely to run into space shortages from dislocated data alignment. ; ; >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ; setup defines and macros and stuff ; Okay, I spent a freakin' weekend trying to figure out this Z80 engine ; (cause I just love it so much ;) ), and this is pretty much everything I've ; got; it's probably about 95% figured out. ; - I didn't do 68K queueing completely... it's in there, I'm just a little fuzzy right now ; I briefly touched the Saxman decoder though I'm not using it; I figured someone ; else can play with that. I think playing music out of ROM is just dandy, ; even if it does require a little post-processing to work. And actually, with ; some tweaks, I think I can get this beast on relative addresses... heheheh ; LOTS of decoding work and relabelling of unknowns! This is a much more complete disasm ;) ; zComRange: @ 1B80h ; +00h -- Priority of current SFX (cleared when 1-up song is playing) ; +01h -- tempo clock ; +02h -- current tempo ; +03h -- Pause/unpause flag: 7Fh for pause; 80h for unpause (set from 68K) ; +04h -- total volume levels to continue decreasing volume before fade out considered complete (starts at 28h, works downward) ; +05h -- delay ticker before next volume decrease ; +06h -- communication value ; +07h -- "DAC is updating" flag (set to FFh until completion of DAC track change) ; +08h -- When NOT set to 80h, 68K request new sound index to play ; +09h -- SFX to Play queue slot ; +0Ah -- Play stereo sound queue slot ; +0Bh -- Unknown SFX Queue slot ; +0Ch -- Address to table of voices ; ; +0Eh -- Set to 80h while fading in (disabling SFX) then 00h ; +0Fh -- Same idea as +05h, except for fade IN ; +10h -- Same idea as +04h, except for fade IN ; +11h -- 80h set indicating 1-up song is playing (stops other sounds) ; +12h -- main tempo value ; +13h -- original tempo for speed shoe restore ; +14h -- Speed shoes flag ; +15h -- If 80h, FM Channel 6 is NOT in use (DAC enabled) ; +16h -- value of which music bank to use (0 for MusicPoint1, $80 for MusicPoint2) ; +17h -- Pal mode flag ; ; ** zTracksStart starts @ +18h ; ; 1B98 base ; Track 1 = DAC ; Then 6 FM ; Then 3 PSG ; ; ; 1B98 = DAC ; 1BC2 = FM 1 ; 1BEC = FM 2 ; 1C16 = FM 3 ; 1C40 = FM 4 ; 1C6A = FM 5 ; 1C94 = FM 6 ; 1CBE = PSG 1 ; 1CE8 = PSG 2 ; 1D12 = PSG 3 (tone or noise) ; ; 1D3C = SFX FM 3 ; 1D66 = SFX FM 4 ; 1D90 = SFX FM 5 ; 1DBA = SFX PSG 1 ; 1DE4 = SFX PSG 2 ; 1E0E = SFX PSG 3 (tone or noise) ; ; zTrack STRUCT DOTS ; "playback control"; bits: ; 1 (02h): seems to be "track is at rest" ; 2 (04h): SFX is overriding this track ; 3 (08h): modulation on ; 4 (10h): do not attack next note ; 7 (80h): track is playing PlaybackControl: ds.b 1 ; "voice control"; bits: ; 2 (04h): If set, bound for part II, otherwise 0 (see zWriteFMIorII) ; -- bit 2 has to do with sending key on/off, which uses this differentiation bit directly ; 7 (80h): PSG Track VoiceControl: ds.b 1 TempoDivider: ds.b 1 ; timing divisor; 1 = Normal, 2 = Half, 3 = Third... DataPointerLow: ds.b 1 ; Track's position low byte DataPointerHigh: ds.b 1 ; Track's position high byte Transpose: ds.b 1 ; Transpose (from coord flag E9) Volume: ds.b 1 ; channel volume (only applied at voice changes) AMSFMSPan: ds.b 1 ; Panning / AMS / FMS settings VoiceIndex: ds.b 1 ; Current voice in use OR current PSG tone VolFlutter: ds.b 1 ; PSG flutter (dynamically effects PSG volume for decay effects) StackPointer: ds.b 1 ; "Gosub" stack position offset (starts at 2Ah, i.e. end of track, and each jump decrements by 2) DurationTimeout: ds.b 1 ; current duration timeout; counting down to zero SavedDuration: ds.b 1 ; last set duration (if a note follows a note, this is reapplied to 0Bh) ; ; ; 0Dh / 0Eh change a little depending on track -- essentially they hold data relevant to the next note to play SavedDAC: ; DAC: Next drum to play FreqLow: ds.b 1 ; FM/PSG: frequency low byte FreqHigh: ds.b 1 ; FM/PSG: frequency high byte NoteFillTimeout: ds.b 1 ; Currently set note fill; counts down to zero and then cuts off note NoteFillMaster: ds.b 1 ; Reset value for current note fill ModulationPtrLow: ds.b 1 ; low byte of address of current modulation setting ModulationPtrHigh: ds.b 1 ; high byte of address of current modulation setting ModulationWait: ds.b 1 ; Wait for ww period of time before modulation starts ModulationSpeed: ds.b 1 ; Modulation Speed ModulationDelta: ds.b 1 ; Modulation change per Mod. Step ModulationSteps: ds.b 1 ; Number of steps in modulation (divided by 2) ModulationValLow: ds.b 1 ; Current modulation value low byte ModulationValHigh: ds.b 1 ; Current modulation value high byte Detune: ds.b 1 ; Set by detune coord flag E1; used to add directly to FM/PSG frequency VolTLMask: ds.b 1 ; zVolTLMaskTbl value set during voice setting (value based on algorithm indexing zGain table) PSGNoise: ds.b 1 ; PSG noise setting VoicePtrLow: ds.b 1 ; low byte of custom voice table (for SFX) VoicePtrHigh: ds.b 1 ; high byte of custom voice table (for SFX) TLPtrLow: ds.b 1 ; low byte of where TL bytes of current voice begin (set during voice setting) TLPtrHigh: ds.b 1 ; high byte of where TL bytes of current voice begin (set during voice setting) LoopCounters: ds.b $A ; Loop counter index 0 ; ... open ... GoSubStack: ; start of next track, every two bytes below this is a coord flag "gosub" (F8h) return stack ; ; The bytes between +20h and +29h are "open"; starting at +20h and going up are possible loop counters ; (for coord flag F7) while +2Ah going down (never AT 2Ah though) are stacked return addresses going ; down after calling coord flag F8h. Of course, this does mean collisions are possible with either ; or other track memory if you're not careful with these! No range checking is performed! ; ; All tracks are 2Ah bytes long zTrack ENDSTRUCT zVar STRUCT DOTS SFXPriorityVal: ds.b 1 TempoTimeout: ds.b 1 CurrentTempo: ds.b 1 ; Stores current tempo value here StopMusic: ds.b 1 ; Set to 7Fh to pause music, set to 80h to unpause. Otherwise 00h FadeOutCounter: ds.b 1 FadeOutDelay: ds.b 1 Communication: ds.b 1 ; Unused byte used to synchronise gameplay events with music DACUpdating: ds.b 1 ; Set to FFh while DAC is updating, then back to 00h QueueToPlay: ds.b 1 ; if NOT set to 80h, means new index was requested by 68K SFXToPlay: ds.b 1 ; When Genesis wants to play "normal" sound, it writes it here SFXStereoToPlay: ds.b 1 ; When Genesis wants to play alternating stereo sound, it writes it here SFXUnknown: ds.b 1 ; Unknown type of sound queue, but it's in Genesis code like it was once used VoiceTblPtr: ds.b 2 ; address of the voices FadeInFlag: ds.b 1 FadeInDelay: ds.b 1 FadeInCounter: ds.b 1 1upPlaying: ds.b 1 TempoMod: ds.b 1 TempoTurbo: ds.b 1 ; Stores the tempo if speed shoes are acquired (or 7Bh is played anywho) SpeedUpFlag: ds.b 1 DACEnabled: ds.b 1 MusicBankNumber: ds.b 1 IsPalFlag: ds.b 1 ; I think this flags if system is PAL zVar ENDSTRUCT ; equates: standard (for Genesis games) addresses in the memory map zYM2612_A0 = $4000 zYM2612_D0 = $4001 zYM2612_A1 = $4002 zYM2612_D1 = $4003 zBankRegister = $6000 zPSG = $7F11 zROMWindow = $8000 ; more equates: addresses specific to this program (besides labelled addresses) zMusicData = $1380 ; don't change this unless you change all the pointers in the BINCLUDE'd music too... zStack = zMusicData+$800 ; 1B80h phase zStack zAbsVar: zVar zTracksStart: ; This is the beginning of all BGM track memory zSongDACFMStart: zSongDAC: zTrack zSongFMStart: zSongFM1: zTrack zSongFM2: zTrack zSongFM3: zTrack zSongFM4: zTrack zSongFM5: zTrack zSongFM6: zTrack zSongFMEnd: zSongDACFMEnd: zSongPSGStart: zSongPSG1: zTrack zSongPSG2: zTrack zSongPSG3: zTrack zSongPSGEnd: zTracksEnd: zTracksSFXStart: zSFX_FMStart: zSFX_FM3: zTrack zSFX_FM4: zTrack zSFX_FM5: zTrack zSFX_FMEnd: zSFX_PSGStart: zSFX_PSG1: zTrack zSFX_PSG2: zTrack zSFX_PSG3: zTrack zSFX_PSGEnd: zTracksSFXEnd: zTracksSaveStart: ; When extra life plays, it backs up a large amount of memory (all track data plus 36 bytes) zSaveVar: zVar zSaveSongDAC: zTrack zSaveSongFM1: zTrack zSaveSongFM2: zTrack zSaveSongFM3: zTrack zSaveSongFM4: zTrack zSaveSongFM5: zTrack zSaveSongFM6: zTrack zSaveSongPSG1: zTrack zSaveSongPSG2: zTrack zSaveSongPSG3: zTrack zTracksSaveEnd: ; see the very end for another set of variables dephase MUSIC_TRACK_COUNT = (zTracksEnd-zTracksStart)/zTrack.len MUSIC_DAC_FM_TRACK_COUNT = (zSongDACFMEnd-zSongDACFMStart)/zTrack.len MUSIC_FM_TRACK_COUNT = (zSongFMEnd-zSongFMStart)/zTrack.len MUSIC_PSG_TRACK_COUNT = (zSongPSGEnd-zSongPSGStart)/zTrack.len SFX_TRACK_COUNT = (zTracksSFXEnd-zTracksSFXStart)/zTrack.len SFX_FM_TRACK_COUNT = (zSFX_FMEnd-zSFX_FMStart)/zTrack.len SFX_PSG_TRACK_COUNT = (zSFX_PSGEnd-zSFX_PSGStart)/zTrack.len ; in what I believe is an unfortunate design choice in AS, ; both the phased and unphased PCs must be within the target processor's range, ; which means phase is useless here despite being designed to fix this problem... ; oh well, I set it up to fix this later when processing the .p file !org 0 ; Z80 code starting at address 0 has special meaning to s2p2bin.exe CPU Z80UNDOC listing purecode ; macro to perform a bank switch... after using this, ; the start of zROMWindow points to the start of the given 68k address, ; rounded down to the nearest $8000 byte boundary bankswitch macro addr68k xor a ; a = 0 ld e,1 ; e = 1 ld hl,zBankRegister cnt := 0 rept 9 ; this is either ld (hl),a or ld (hl),e db (73h|((((addr68k)&(1<<(15+cnt)))==0)<<2)) cnt := (cnt+1) endm endm ; macro to make a certain error message clearer should you happen to get it... rsttarget macro {INTLABEL} if ($&7)||($>38h) fatal "Function __LABEL__ is at 0\{$}h, but must be at a multiple of 8 bytes <= 38h to be used with the rst instruction." endif if "__LABEL__"<>"" __LABEL__ label $ endif endm ; function to decide whether an offset's full range won't fit in one byte offsetover1byte function from,maxsize, ((from&0FFh)>(100h-maxsize)) ; macro to make sure that ($ & 0FF00h) == (($+maxsize) & 0FF00h) ensure1byteoffset macro maxsize if offsetover1byte($,maxsize) startpad := $ align 100h if MOMPASS=1 endpad := $ if endpad-startpad>=1h ; warn because otherwise you'd have no clue why you're running out of space so fast warning "had to insert \{endpad-startpad}h bytes of padding before improperly located data at 0\{startpad}h in Z80 code" endif endif endif endm ; function to turn a 68k address into a word the Z80 can use to access it, ; assuming the correct bank has been switched to first zmake68kPtr function addr,zROMWindow+(addr&7FFFh) ; >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ; Z80 'ROM' start: ;zEntryPoint: di ; disable interrupts ld sp,zStack jp zloc_167 ; --------------------------------------------------------------------------- ; zbyte_7: zPalModeByte: db 0 ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| if OptimiseDriver=0 ; This is redundant: the Z80 is slow enough to not need to worry about this align 8 ;zsub_8 zFMBusyWait: rsttarget ; Performs the annoying task of waiting for the FM to not be busy ld a,(zYM2612_A0) add a,a jr c,zFMBusyWait ret ; End of function zFMBusyWait endif ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| align 8 ;zsub_10 zWriteFMIorII: rsttarget bit 2,(ix+zTrack.VoiceControl) jr z,zWriteFMI jr zWriteFMII ; End of function zWriteFMIorII ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| align 8 ;zsub_18 zWriteFMI: rsttarget ; Write reg/data pair to part I; 'a' is register, 'c' is data if OptimiseDriver=0 push af rst zFMBusyWait ; 'rst' is like 'call' but only works for 8-byte aligned addresses <= 38h pop af endif ld (zYM2612_A0),a push af if OptimiseDriver=0 rst zFMBusyWait endif ld a,c ld (zYM2612_D0),a pop af ret ; End of function zWriteFMI ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| align 8 ;zsub_28 zWriteFMII: rsttarget ; Write reg/data pair to part II; 'a' is register, 'c' is data if OptimiseDriver=0 push af rst zFMBusyWait pop af endif ld (zYM2612_A1),a push af if OptimiseDriver=0 rst zFMBusyWait endif ld a,c ld (zYM2612_D1),a pop af ret ; End of function zWriteFMII ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| org 38h zVInt: rsttarget ; This is called every VBLANK (38h is the interrupt entry point, ; and VBLANK is the only one Z80 is hooked up to.) push af ; Save 'af' exx ; Effectively backs up 'bc', 'de', and 'hl' call zBankSwitchToMusic ; Bank switch to the music (depending on which BGM is playing in my version) xor a ; Clear 'a' ld (zDoSFXFlag),a ; Not updating SFX (updating music) ld ix,zAbsVar ; ix points to zComRange ld a,(zAbsVar.StopMusic) ; Get pause/unpause flag or a ; test 'a' jr z,zUpdateEverything ; If zero, go to zUpdateEverything call zPauseMusic jp zUpdateDAC ; Now update the DAC ; --------------------------------------------------------------------------- ;zloc_51 zUpdateEverything: ld a,(zAbsVar.FadeOutCounter) ; are we fading out? or a call nz,zUpdateFadeout ; If so, update that ld a,(zAbsVar.FadeInFlag) ; are we fading in? or a call nz,zUpdateFadeIn ; If so, update that ld a,(zAbsVar.SFXToPlay) ; zComRange+09h -- play normal sound or (ix+zVar.SFXStereoToPlay) ; zComRange+0Ah -- play stereo sound (alternating speakers) or (ix+zVar.SFXUnknown) ; zComRange+0Bh -- "unknown" slot call nz,zCycleQueue ; If any of those are non-zero, cycle queue ; Apparently if this is 80h, it does not play anything new, ; otherwise it cues up the next play (flag from 68K for new item) ld a,(zAbsVar.QueueToPlay) cp 80h call nz,zPlaySoundByIndex ; If not 80h, we need to play something new! ; Spindash update ld a,(zSpindashPlayingCounter) or a jr z,+ ; if the spindash counter is already 0, branch dec a ; decrease the spindash sound playing counter ld (zSpindashPlayingCounter),a + ; If the system is PAL, then this performs some timing adjustments ; (i.e. you need to update 1.2x as much to keep up the same rate) ld hl,zPalModeByte ; Get address of zPalModeByte ld a,(zAbsVar.IsPalFlag) ; Get IsPalFlag -> 'a' and (hl) ; 'And' them together jr z,+ ; If it comes out zero, do nothing ld hl,zPALUpdTick dec (hl) jr nz,+ ld (hl),5 ; every 6 frames (0-5) you need to "double update" to sort of keep up call zUpdateMusic + call zUpdateMusic ; Now all of the SFX tracks are updated in a similar manner to "zUpdateMusic"... bankswitch SoundIndex ; Bank switch to sound effects ld a,80h ld (zDoSFXFlag),a ; Set zDoSFXFlag = 80h (updating sound effects) ; FM SFX channels ld b,SFX_FM_TRACK_COUNT ; Only 3 FM channels for SFX (FM3, FM4, FM5) - push bc ld de,zTrack.len ; Spacing between tracks add ix,de ; Next track bit 7,(ix+zTrack.PlaybackControl) ; Is it playing? call nz,zFMUpdateTrack ; If it is, go update it pop bc djnz - ; PSG SFX channels ld b,SFX_PSG_TRACK_COUNT ; All PSG channels available - push bc ld de,zTrack.len ; Spacing between tracks add ix,de ; Next track bit 7,(ix+zTrack.PlaybackControl) ; Is it playing? call nz,zPSGUpdateTrack ; If it is, go update it pop bc djnz - ; Now we update the DAC... this only does anything if there's a new DAC ; sound to be played. This is called after updating the DAC track. ; Otherwise it just mucks with the timing loop, forcing an update. zUpdateDAC: bankswitch SndDAC_Start ; Bankswitch to the DAC data ld a,(zCurDAC) ; Get currently playing DAC sound or a jp m,+ ; If one is queued (80h+), go to it! exx ; Otherwise restore registers from mirror regs ld b,1 ; b=1 (initial feed to the DAC "djnz" loops, i.e. UPDATE RIGHT AWAY) pop af ei ; enable interrupts ret + ; If you get here, it's time to start a new DAC sound... ld a,80h ex af,af' ;' ld a,(zCurDAC) ; Get current DAC sound sub 81h ; Subtract 81h (first DAC index is 81h) ld (zCurDAC),a ; Store that as current DAC sound ; The following two instructions are dangerous: they discard the upper ; two bits of zCurDAC, meaning you can only have 40h DAC samples. add a,a add a,a ; a *= 4 (each DAC entry is a pointer and length, 2+2) add a,zDACPtrTbl&0FFh ; Get low byte into table -> 'a' ld (zloc_104+1),a ; store into the instruction after zloc_104 (self-modifying code) add a,zDACLenTbl-zDACPtrTbl ; How to offset to length versus pointer ld (zloc_107+2),a ; store into the instruction after zloc_107 (self-modifying code) pop af ld hl,zWriteToDAC ex (sp),hl ; Jump to zWriteToDAC zloc_104: ld hl,(zDACPtrTbl) ; "self-modified code" -- sets start address of DAC sample for zWriteToDAC zloc_107: ld de,(zDACLenTbl) ; "self-modified code" -- sets length of DAC sample for zWriteToDAC zloc_10B: ld bc,100h ; "self-modified code" -- From zloc_22A; sets b=1 (the 100h part of it) UPDATE RIGHT AWAY and c="data rate delay" for this DAC sample, the future 'b' setting ei ; enable interrupts ret ; End of function zVInt ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ; Updates all tracks; queues notes and durations! ;zsub_110 zUpdateMusic: call TempoWait ; This is a tempo waiting function ; DAC updates ld a,0FFh ld (zAbsVar.DACUpdating),a ; Store FFh to DACUpdating ld ix,zTracksStart ; Point "ix" to zTracksStart bit 7,(ix+zTrack.PlaybackControl) ; Is bit 7 (80h) set on playback control byte? (means "is playing") call nz,zDACUpdateTrack ; If so, zDACUpdateTrack xor a ; Clear a ld (zAbsVar.DACUpdating),a ; Store 0 to DACUpdating ld b,MUSIC_FM_TRACK_COUNT ; Loop 6 times (FM)... - push bc ld de,zTrack.len ; Space between tracks add ix,de ; Go to next track bit 7,(ix+zTrack.PlaybackControl) ; Is bit 7 (80h) set on playback control byte? (means "is playing") call nz,zFMUpdateTrack ; If so... pop bc djnz - ld b,MUSIC_PSG_TRACK_COUNT ; Loop 3 times (PSG)... - push bc ld de,zTrack.len ; Space between tracks add ix,de ; Go to next track bit 7,(ix+zTrack.PlaybackControl) ; Is this track playing? call nz,zPSGUpdateTrack ; If so... pop bc djnz - ret ; End of function zUpdateMusic ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_14C TempoWait: ; Tempo works as divisions of the 60Hz clock (there is a fix supplied for ; PAL that "kind of" keeps it on track.) Every time the internal music clock ; overflows, it will update. So a tempo of 80h will update every other ; frame, or 30 times a second. ld ix,zAbsVar ; ix points to zComRange ld a,(ix+zVar.CurrentTempo) ; tempo value add a,(ix+zVar.TempoTimeout) ; Adds previous value to ld (ix+zVar.TempoTimeout),a ; Store this as new ret c ; If addition overflowed (answer greater than FFh), return ; So if adding tempo value did NOT overflow, then we add 1 to all durations ld hl,zTracksStart+zTrack.DurationTimeout ; Start at first track's delay counter (counting up to delay) ld de,zTrack.len ; Offset between tracks ld b,MUSIC_TRACK_COUNT ; Loop for all tracks - inc (hl) ; Increasing delay tick counter to target add hl,de ; Next track... djnz - ret ; End of function TempoWait ; --------------------------------------------------------------------------- zloc_167: im 1 ; set interrupt mode 1 call zClearTrackPlaybackMem ei ; enable interrupts ld iy,zDACDecodeTbl ld de,0 ; This controls the update rate for the DAC... ; My speculation for the rate at which the DAC updates: ; Z80 clock = 3.57954MHz = 3579540Hz (not sure?) ; zWaitLoop (immediately below) is waiting for someone to set ; 'de' (length of DAC sample) to non-zero ; The DAC code is sync'ed with VBLANK somehow, but I haven't quite got that ; one figure out yet ... tests on emulator seem to confirm it though. ; Next, there are "djnz" loops which do busy-waits. (Two of them, which is ; where the '2' comes from in my guess equation.) The DACMasterPlaylist ; appears to use '1' as the lowest input value to these functions. (Which, ; given the djnz, would be the fastest possible value.) ; The rate seems to be calculated by 3579540Hz / (60Hz + (speed * 4)) / 2 ; This "waitLoop" waits if the DAC has no data, or else it drops out! ; zloc_174: zWaitLoop: ld a,d or e jr z,zWaitLoop ; As long as 'de' (length of sample) = 0, wait... ; 'hl' is the pointer to the sample, 'de' is the length of the sample, ; and 'iy' points to the translation table; let's go... ; The "djnz $" loops control the playback rate of the DAC ; (the higher the 'b' value, the slower it will play) ; As for the actual encoding of the data, it is described by jman2050: ; "As for how the data is compressed, lemme explain that real quick: ; First, it is a lossy compression. So if you recompress a PCM sample this way, ; you will lose precision in data. Anyway, what happens is that each compressed data ; is separated into nybbles (1 4-bit section of a byte). This first nybble of data is ; read, and used as an index to a table containing the following data: ; 0,1,2,4,8,$10,$20,$40,$80,$FF,$FE,$FC,$F8,$F0,$E0,$C0." [zDACDecodeTbl / zbyte_1B3] ; "So if the nybble were equal to F, it'd extract $C0 from the tale. If it were 8, ; it would extract $80 from the table. ... Anyway, there is also another byte of data ; that we'll call 'd'. At the start of decompression, d is $80. What happens is that d ; is then added to the data extracted from the table using the nybble. So if the nybble ; were 4, the 8 would be extracted from the table, then added to d, which is $80, ; resulting in $88. This result is then put back into d, then fed into the YM2612 for ; processing. Then the next nybble is read, the data is extracted from the table, then ; is added to d (remember, d is now changed because of the previous operation), then is ; put back into d, then is fed into the YM2612. This process is repeated until the number ; of bytes as defined in the table above are read and decompressed." ; In our case, the so-called 'd' value is shadow register 'a' zWriteToDAC: djnz $ ; Busy wait for specific amount of time in 'b' di ; disable interrupts (while updating DAC) ld a,2Ah ; DAC port ld (zYM2612_A0),a ; Set DAC port register ld a,(hl) ; Get next DAC byte rlca rlca rlca rlca and 0Fh ; UPPER 4-bit offset into zDACDecodeTbl ld (zloc_18B+2),a ; store into the instruction after zloc_18B (self-modifying code) ex af,af' ; shadow register 'a' is the 'd' value for 'jman2050' encoding zloc_18B: add a,(iy+0) ; Get byte from zDACDecodeTbl (self-modified to proper index) ld (zYM2612_D0),a ; Write this byte to the DAC ex af,af' ; back to regular registers ld b,c ; reload 'b' with wait value ei ; enable interrupts (done updating DAC, busy waiting for next update) djnz $ ; Busy wait for specific amount of time in 'b' di ; disable interrupts (while updating DAC) push af pop af ld a,2Ah ; DAC port ld (zYM2612_A0),a ; Set DAC port register ld b,c ; reload 'b' with wait value ld a,(hl) ; Get next DAC byte inc hl ; Next byte in DAC stream... dec de ; One less byte and 0Fh ; LOWER 4-bit offset into zDACDecodeTbl ld (zloc_1A8+2),a ; store into the instruction after zloc_1A8 (self-modifying code) ex af,af' ; shadow register 'a' is the 'd' value for 'jman2050' encoding zloc_1A8: add a,(iy+0) ; Get byte from zDACDecodeTbl (self-modified to proper index) ld (zYM2612_D0),a ; Write this byte to the DAC ex af,af' ; back to regular registers ei ; enable interrupts (done updating DAC, busy waiting for next update) jp zWaitLoop ; Back to the wait loop; if there's more DAC to write, we come back down again! ; --------------------------------------------------------------------------- ; 'jman2050' DAC decode lookup table ;zbyte_1B3 zDACDecodeTbl: db 0, 1, 2, 4, 8, 10h, 20h, 40h db 80h, -1, -2, -4, -8, -10h, -20h, -40h ; The following two tables are used for when an SFX terminates ; its track to properly restore the music track it temporarily took ; over. Note that an important rule here is that no SFX may use ; DAC, FM Channel 1, FM Channel 2, or FM Channel 6, period. ; Thus there's also only SFX tracks starting at FM Channel 3. ; The zeroes appear after FM 3 because it calculates the offsets into ; these tables by their channel assignment, where between Channel 3 ; and Channel 4 there is a gap numerically. ensure1byteoffset 10h ;zbyte_1C3 zMusicTrackOffs: ; These are offsets to different music tracks starting with FM3 dw zSongFM3, 0000h, zSongFM4, zSongFM5 ; FM3, 0, FM4, FM5 dw zSongPSG1, zSongPSG2, zSongPSG3, zSongPSG3 ; PSG1, PSG2, PSG3, PSG3 (noise alternate) ensure1byteoffset 10h ;zbyte_1D3 zSFXTrackOffs: ; These are offsets to different sound effect tracks starting with FM3 dw zSFX_FM3, 0000h, zSFX_FM4, zSFX_FM5 ; FM3, 0, FM4, FM5 dw zSFX_PSG1, zSFX_PSG2, zSFX_PSG3, zSFX_PSG3 ; PSG1, PSG2, PSG3, PSG3 (noise alternate) ; --------------------------------------------------------------------------- zDACUpdateTrack: dec (ix+zTrack.DurationTimeout) ; Subtract 1 from (zTracksStart+0Bh) [Track 1's delay start] ret nz ; Return if not zero yet ld l,(ix+zTrack.DataPointerLow) ; Low byte of DAC track current address (zTracksStart+3) ld h,(ix+zTrack.DataPointerHigh) ; High byte of DAC track current address (zTracksStart+4) - ld a,(hl) ; Get next byte from DAC Track inc hl ; Move to next position... cp 0E0h ; Check if is coordination flag jr c,+ ; Not coord flag? Skip to '+' call zCoordFlag ; Handle coordination flag jp - ; Loop back around... + or a ; Test 'a' for 80h not set, which is a note duration jp p,zloc_20E ; If note duration, jump to zloc_20E (note that "hl" is already incremented) ld (ix+zTrack.SavedDAC),a ; This is a note; store it here ld a,(hl) ; Get next byte... or a ; Test 'a' for 80h not set, which is a note duration jp p,zloc_20D ; Is this a duration this time?? If so, jump to zloc_20D (only difference is to increment "hl") ; Note followed a note... apparently recycles the previous duration ld a,(ix+zTrack.SavedDuration) ; Current DAC note ticker goal value -> 'a' ld (ix+zTrack.DurationTimeout),a ; Use it again jr zDACAfterDur ; Jump to after duration subroutine... ; --------------------------------------------------------------------------- zloc_20D: inc hl ; Goes to next byte (after duration byte) zloc_20E: call zSetDuration ;zloc_211 zDACAfterDur: ld (ix+zTrack.DataPointerLow),l ; Stores "hl" to the DAC track pointer memory ld (ix+zTrack.DataPointerHigh),h bit 2,(ix+zTrack.PlaybackControl) ; Is SFX overriding this track? ret nz ; If so, we're done ld a,(ix+zTrack.SavedDAC) ; Check next note to play cp 80h ; Is it a rest? ret z ; If so, quit sub 81h ; Otherwise, transform note into an index... (we're selecting which drum to play!) add a,a ; Multiply by 2... add a,zDACMasterPlaylist&0FFh ; Offset into list ld (zloc_22A+2),a ; store into the instruction after zloc_22A (self-modifying code) zloc_22A: ld bc,(zDACMasterPlaylist) ; Load appropriate drum info -> bc ld a,c ; DAC sample number (81h base) -> 'a' ld (zCurDAC),a ; Store current DAC sound to play ld a,b ; Data rate delay -> 'b' ld (zloc_10B+1),a ; store into the instruction after zloc_10B (self-modifying code) ret ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_237 zFMUpdateTrack: dec (ix+zTrack.DurationTimeout) ; Decrement duration jr nz,+ ; If not time-out yet, go do updates only res 4,(ix+zTrack.PlaybackControl) ; When duration over, clear "do not attack" bit 4 (0x10) of track's play control call zFMDoNext ; Handle coordination flags, get next note and duration call zFMPrepareNote ; Prepares to play next note call zFMNoteOn ; Actually key it (if allowed) call zDoModulation ; Update modulation (if modulation doesn't change, we do not return here) jp zFMUpdateFreq ; Applies frequency update from modulation + call zNoteFillUpdate ; Applies "note fill" (time until cut-off); NOTE: Will not return here if "note fill" expires call zDoModulation ; Update modulation (if modulation doesn't change, we do not return here) jp zFMUpdateFreq ; Applies frequency update from modulation ; End of function zFMUpdateTrack ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_258 zFMDoNext: ld l,(ix+zTrack.DataPointerLow) ; Load track position low byte ld h,(ix+zTrack.DataPointerHigh) ; Load track position high byte res 1,(ix+zTrack.PlaybackControl) ; Clear bit 1 (02h) "track is rest" from track - ld a,(hl) inc hl ; Increment track to next byte cp 0E0h ; Is it a control byte / "coordination flag"? jr c,+ ; If not, jump over call zCoordFlag ; Handle coordination flag jr - ; Go around, get next byte + push af call zFMNoteOff ; Send key off pop af or a ; Test 'a' for 80h not set, which is a note duration jp p,+ ; If duration, jump to '+' call zFMSetFreq ; Otherwise, this is a note; call zFMSetFreq ld a,(hl) ; Get next byte or a ; Test 'a' for 80h set, which is a note jp m,zFinishTrackUpdate ; If this is a note, jump to zFinishTrackUpdate inc hl ; Otherwise, go to next byte; a duration + call zSetDuration jp zFinishTrackUpdate ; Either way, jumping to zFinishTrackUpdate... ; End of function zFMDoNext ; --------------------------------------------------------------------------- ; zloc_285: ;zGetFrequency zFMSetFreq: ; 'a' holds a note to get frequency for sub 80h jr z,zFMDoRest ; If this is a rest, jump to zFMDoRest add a,(ix+zTrack.Transpose) ; Add current channel transpose (coord flag E9) add a,a ; Offset into Frequency table... if OptimiseDriver ld d,12*2 ; 12 notes per octave ld c,0 ; clear c (will hold octave bits) - sub d ; Subtract 1 octave from the note jr c,+ ; If this is less than zero, we are done inc c ; One octave up jr - + add a,d ; Add 1 octave back (so note index is positive) sla c sla c sla c ; multiply octave value by 8, to get final octave bits endif add a,zFrequencies&0FFh ld (zloc_292+2),a ; store into the instruction after zloc_292 (self-modifying code) ; ld d,a ; adc a,(zFrequencies&0FF00h)>>8 ; sub d ; ld (zloc_292+3),a ; this is how you could store the high byte of the pointer too (unnecessary if it's in the right range) zloc_292: ld de,(zFrequencies) ; Stores frequency into "de" ld (ix+zTrack.FreqLow),e ; Frequency low byte -> trackPtr + 0Dh if OptimiseDriver ld a,d or c ld (ix+zTrack.FreqHigh),a ; Frequency high byte -> trackPtr + 0Eh else ld (ix+zTrack.FreqHigh),d ; Frequency high byte -> trackPtr + 0Eh endif ret ; --------------------------------------------------------------------------- ;zloc_29D zFMDoRest: set 1,(ix+zTrack.PlaybackControl) ; Set bit 1 (track is at rest) xor a ; Clear 'a' ld (ix+zTrack.FreqLow),a ; Zero out FM Frequency ld (ix+zTrack.FreqHigh),a ; Zero out FM Frequency ret ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_2A9 zSetDuration: ld c,a ; 'a' = current duration ld b,(ix+zTrack.TempoDivider) ; Divisor; causes multiplication of duration for every number higher than 1 - djnz + ld (ix+zTrack.SavedDuration),a ; Store new duration into ticker goal of this track (this is reused if a note follows a note without a new duration) ld (ix+zTrack.DurationTimeout),a ; Sets it on ticker (counts to zero) ret + add a,c ; Will multiply duration based on 'b' jp - ; End of function zSetDuration ; --------------------------------------------------------------------------- ;zloc_2BA zFinishTrackUpdate: ; Common finish-up routine used by FM or PSG ld (ix+zTrack.DataPointerLow),l ; Stores "hl" to the track pointer memory ld (ix+zTrack.DataPointerHigh),h ld a,(ix+zTrack.SavedDuration) ; Last set duration ld (ix+zTrack.DurationTimeout),a ; ... put into ticker bit 4,(ix+zTrack.PlaybackControl) ; Is bit 4 (10h) "do not attack next note" set on playback? ret nz ; If so, quit ld a,(ix+zTrack.NoteFillMaster) ; Master "note fill" value -> a ld (ix+zTrack.NoteFillTimeout),a ; Reset 0Fh "note fill" value to master ld (ix+zTrack.VolFlutter),0 ; Reset PSG flutter byte bit 3,(ix+zTrack.PlaybackControl) ; is modulation turned on? ret z ; if not, quit ld l,(ix+zTrack.ModulationPtrLow) ; Otherwise, get address of modulation setting ld h,(ix+zTrack.ModulationPtrHigh) jp zSetModulation ; ... and go do it! ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_2E3 zNoteFillUpdate: ld a,(ix+zTrack.NoteFillTimeout) ; Get current note fill value or a ret z ; If zero, return! dec (ix+zTrack.NoteFillTimeout) ; Decrement note fill ret nz ; If not zero, return set 1,(ix+zTrack.PlaybackControl) ; Set bit 1 (track is at rest) pop de ; return address -> 'de' (will not return to z*UpdateTrack function!!) bit 7,(ix+zTrack.VoiceControl) ; Is this a PSG track? jp nz,zPSGNoteOff ; If so, jump to zPSGNoteOff jp zFMNoteOff ; Else, jump to zFMNoteOff ; End of function zNoteFillUpdate ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_2FB zDoModulation: pop de ; keep return address -> de (MAY not return to caller) bit 1,(ix+zTrack.PlaybackControl) ; Is "track in rest"? ret nz ; If so, quit bit 3,(ix+zTrack.PlaybackControl) ; Is modulation on? ret z ; If not, quit ld a,(ix+zTrack.ModulationWait) ; 'ww' period of time before modulation starts or a jr z,+ ; if zero, go to it! dec (ix+zTrack.ModulationWait) ; Otherwise, decrement timer ret ; return if decremented (does NOT return to z*UpdateTrack!!) + dec (ix+zTrack.ModulationSpeed) ; Decrement modulation speed counter ret nz ; Return if not yet zero ld l,(ix+zTrack.ModulationPtrLow) ld h,(ix+zTrack.ModulationPtrHigh) ; 'hl' points to modulation setting inc hl ; skip passed 'ww' period of time ld a,(hl) ; Get modulation speed ld (ix+zTrack.ModulationSpeed),a ; Restore speed counter ld a,(ix+zTrack.ModulationSteps) ; Get number of steps in modulation or a jr nz,+ ; If not zero, skip to '+' ; If steps have reached zero... inc hl ; passed mod speed inc hl ; passed mod change per mod step ld a,(hl) ; get number of steps in modulation ld (ix+zTrack.ModulationSteps),a ; restore modulation steps ld a,(ix+zTrack.ModulationDelta) ; get modulation change per mod step neg ; flip it negative ld (ix+zTrack.ModulationDelta),a ; store negated value ret + dec (ix+zTrack.ModulationSteps) ; Decrement the step ld l,(ix+zTrack.ModulationValLow) ld h,(ix+zTrack.ModulationValHigh) ; Get 16-bit modulation value ; This is a 16-bit sign extension for 'bc' if OptimiseDriver ld a,(ix+zTrack.ModulationDelta) ; Get current modulation change per step -> 'a' ld c,a rla ; Carry contains sign of delta sbc a,a ; a = 0 or -1 if carry is 0 or 1 ld b,a ; bc = sign extension of delta else ld b,0 ld c,(ix+zTrack.ModulationDelta) ; Get current modulation change per step -> 'c' bit 7,c jp z,+ ld b,0FFh ; Sign extend if negative + endif add hl,bc ; Add to current modulation value ld (ix+zTrack.ModulationValLow),l ld (ix+zTrack.ModulationValHigh),h ; Store new 16-bit modulation value ld c,(ix+zTrack.FreqLow) ; frequency low byte -> c ld b,(ix+zTrack.FreqHigh) ; frequency high byte -> b add hl,bc ; Add modulation value ex de,hl jp (hl) ; WILL return to z*UpdateTrack ; End of function zDoModulation ; --------------------------------------------------------------------------- ; This the note -> frequency setting lookup ; the same array is found at $729CE in Sonic 1, and at $C9C44 in Ristar ; zword_359: ensure1byteoffset 8Ch zPSGFrequencies: dw 356h, 326h, 2F9h, 2CEh, 2A5h, 280h, 25Ch, 23Ah, 21Ah, 1FBh, 1DFh, 1C4h dw 1ABh, 193h, 17Dh, 167h, 153h, 140h, 12Eh, 11Dh, 10Dh, 0FEh, 0EFh, 0E2h dw 0D6h, 0C9h, 0BEh, 0B4h, 0A9h, 0A0h, 97h, 8Fh, 87h, 7Fh, 78h, 71h dw 6Bh, 65h, 5Fh, 5Ah, 55h, 50h, 4Bh, 47h, 43h, 40h, 3Ch, 39h dw 36h, 33h, 30h, 2Dh, 2Bh, 28h, 26h, 24h, 22h, 20h, 1Fh, 1Dh dw 1Bh, 1Ah, 18h, 17h, 16h, 15h, 13h, 12h, 11h, 0 ; --------------------------------------------------------------------------- ;zloc_3E5 zFMPrepareNote: bit 1,(ix+zTrack.PlaybackControl) ; Is track in rest? ret nz ; If so, quit ld e,(ix+zTrack.FreqLow) ; Get frequency low ld d,(ix+zTrack.FreqHigh) ; Get frequency high ld a,d or e jp z,zloc_4C5 ; If de == 0, go to zloc_4C5 ;zloc_3F5 zFMUpdateFreq: bit 2,(ix+zTrack.PlaybackControl) ; Is SFX overriding this track? ret nz ; If so, quit! ; This is a 16-bit sign extension of (ix+19h) if OptimiseDriver ld a,(ix+zTrack.Detune) ; Get detune value ld l,a rla ; Carry contains sign of detune sbc a,a ; a = 0 or -1 if carry is 0 or 1 ld h,a ; hl = sign extension of detune else ld h,0 ; h = 0 ld l,(ix+zTrack.Detune) ; Get detune value bit 7,l ; Did prior value have 80h set? jr z,+ ; If not, skip next step ld h,0FFh ; h = FFh + endif add hl,de ; Alter frequency just a tad ld c,h ; Upper part of frequency as data to FM ('c') ld a,(ix+zTrack.VoiceControl) ; "voice control" byte -> 'a' and 3 ; Strip to only channel assignment add a,0A4h ; Change to proper register rst zWriteFMIorII ; Write it! ld c,l ; lower part of frequency sub 4 ; A0h+ register rst zWriteFMIorII ; Write it! ret ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_414 zPSGUpdateTrack: dec (ix+zTrack.DurationTimeout) ; decrement current duration timeout.. jr nz,+ ; If not time-out yet, go do updates only res 4,(ix+zTrack.PlaybackControl) ; Reset "do not attack next note" bit call zPSGDoNext ; Handle coordination flags, get next note and duration call zPSGDoNoteOn ; Actually key it (if allowed) call zPSGDoVolFX ; This applies PSG volume as well as its special volume-based effects that I call "flutter" call zDoModulation ; Update modulation (if modulation doesn't change, we do not return here) jp zPSGUpdateFreq + call zNoteFillUpdate ; Applies "note fill" (time until cut-off); NOTE: Will not return here if "note fill" expires call zPSGUpdateVolFX ; Update volume effects call zDoModulation ; Update modulation (if modulation doesn't change, we do not return here) jp zPSGUpdateFreq ; End of function zPSGUpdateTrack ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_438 zPSGDoNext: ld l,(ix+zTrack.DataPointerLow) ; Load track position low byte ld h,(ix+zTrack.DataPointerHigh) ; Load track position high byte res 1,(ix+zTrack.PlaybackControl) ; Clear bit 1 (02h) "track is rest" from track - ld a,(hl) inc hl ; Increment track to next byte cp 0E0h ; Is it a control byte / "coordination flag"? jr c,+ ; If not, jump over call zCoordFlag ; Handle coordination flag jr - ; Go around, get next byte + or a ; Test 'a' for 80h not set, which is a note duration jp p,+ ; If note duration, jump to '+' call zPSGSetFreq ; Get frequency for this note ld a,(hl) ; Get next byte or a ; Test 'a' for 80h set, which is a note jp m,zFinishTrackUpdate ; If this is a note, jump to zFinishTrackUpdate inc hl ; Otherwise, go to next byte; a duration + call zSetDuration jp zFinishTrackUpdate ; Either way, jumping to zFinishTrackUpdate... ; End of function zPSGDoNext ; --------------------------------------------------------------------------- ;zloc_460 zPSGSetFreq: sub 81h ; a = a-$81 (zero-based index from lowest note) jr c,+ ; If carry (only time that happens if 80h because of earlier logic) this is a rest! add a,(ix+zTrack.Transpose) ; Add current channel transpose (coord flag E9) add a,a ; Multiply note value by 2 add a,zPSGFrequencies&0FFh ; Point to proper place in table ld (zloc_46D+2),a ; store into the instruction after zloc_46D (self-modifying code) zloc_46D: ld de,(zPSGFrequencies) ; Gets appropriate frequency setting -> 'de' ld (ix+zTrack.FreqLow),e ; Frequency low byte -> trackPtr + 0Dh ld (ix+zTrack.FreqHigh),d ; Frequency high byte -> trackPtr + 0Eh ret + ; If you get here, we're doing a PSG rest set 1,(ix+zTrack.PlaybackControl) ; Set "track in rest" bit ld a,0FFh ld (ix+zTrack.FreqLow),a ; Frequency low byte = FFh ld (ix+zTrack.FreqHigh),a ; Frequency hight byte = FFh jp zPSGNoteOff ; Send PSG Note Off ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_487 zPSGDoNoteOn: bit 7,(ix+zTrack.FreqHigh) ; If track is at rest (frequency was set to FFh)... jr nz,zloc_4C5 ; jump to zloc_4C5 ld e,(ix+zTrack.FreqLow) ; Frequency low byte -> e ld d,(ix+zTrack.FreqHigh) ; Frequency high byte -> d ;zloc_493 zPSGUpdateFreq: ld a,(ix+zTrack.PlaybackControl) ; Get playback control byte and 6 ret nz ; If either bit 1 ("track in rest") and 2 ("SFX overriding this track"), quit! ; This is a 16-bit sign extension of (ix+19h) -> 'hl' if OptimiseDriver ld a,(ix+zTrack.Detune) ; Get detune value ld l,a rla ; Carry contains sign of detune sbc a,a ; a = 0 or -1 if carry is 0 or 1 ld h,a ; hl = sign extension of detune else ld h,0 ld l,(ix+zTrack.Detune) ; hl = detune value (coord flag E9) bit 7,l ; Did prior value have 80h set? jr z,+ ; If not, skip next step ld h,0FFh ; sign extend negative value + endif add hl,de ; Alter frequency just a tad ; This picks out the reg to write to the PSG ld a,(ix+zTrack.VoiceControl) ; Get "voice control" byte... cp 0E0h ; Is it E0h? jr nz,+ ; If not, skip next step ld a,0C0h ; a = C0h instead of E0h + ld b,a ; 'a' -> 'b' ld a,l ; Frequency low byte -> 'a' and 0Fh ; Keep only lower four bits (first PSG reg write only applies d0-d3 of freq) or b ; Apply register bits ld (zPSG),a ; Write it to PSG! ld a,l ; Get frequency low byte -> 'a' srl h ; (h >> 1); lowest bit into carry rra ; (a >> 1); carry from 'h' applied at end srl h ; ... and so on ... rra rra rra ; in C, basically (hl >> 4) (except possible garbage from the rotation in upper bits) and 3Fh ; keep only lower 6 bits (PSG d4-d9) ld (zPSG),a ; Write other frequency byte to PSG! ret ; --------------------------------------------------------------------------- zloc_4C5: set 1,(ix+zTrack.PlaybackControl) ; Set "track at rest" bit ret ; End of function zPSGDoNoteOn ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_4CA zPSGUpdateVolFX: ld a,(ix+zTrack.VoiceIndex) ; Get current PSG tone or a ; Test if it's zero ret z ; If it is, return! ; Otherwise, fall into zPSGDoVolFX... ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_4CF zPSGDoVolFX: ld b,(ix+zTrack.Volume) ; Channel volume -> 'b' ld a,(ix+zTrack.VoiceIndex) ; Current PSG tone -> 'a' or a ; Test it jr z,zPSGUpdateVol ; If tone is zero, jump to zPSGUpdateVol ld hl,zPSG_FlutterTbl ; hl points to zPSG_FlutterTbl table dec a ; a-- add a,a ; a *= 2 ld e,a ld d,0 ; de = a add hl,de ; Offset into pointer table... ld a,(hl) ; Get low byte -> 'a' inc hl ; Next byte ld h,(hl) ; Get high byte into 'h' add a,(ix+zTrack.VolFlutter) ; Apply PSG flutter (provides dynamic volume for special effects) ld l,a adc a,h sub l ld h,a ; Basically, hl = (hl+(ix+zTrack.VolFlutter)) ld a,(hl) ; Get byte from this location inc (ix+zTrack.VolFlutter) ; Increment PSG flutter value or a ; test byte from before jp p,+ ; Is it a positive value? cp 80h ; Check if it's 80h (terminator to the "flutter" list) jr z,zVolEnvHold ; If it is, then jump to zVolEnvHold (which just keeps at this flutter value, i.e. no more changes in volume) + add a,b ; Apply this "flutter" to channel volume -> 'a' ld b,a ; a -> 'b' ;zloc_4F9 zPSGUpdateVol: ld a,(ix+zTrack.PlaybackControl) ; get playback control byte and 6 ret nz ; If either bit 1 ("track in rest") and 2 ("SFX overriding this track"), quit! bit 4,(ix+zTrack.PlaybackControl) ; is "do not attack next note" set? jr nz,zloc_515 ; If so, jump to zloc_515 zloc_505: ld a,b ; 'b' -> 'a' cp 10h ; Did the level get pushed below silence level? (i.e. a > 0Fh) jr c,+ ld a,0Fh ; If so, fix it! + or (ix+zTrack.VoiceControl) ; Apply channel info (which PSG to set!) or 10h ; This bit marks it as an attenuation level assignment (along with channel info just above) ld (zPSG),a ; Write to PSG!! ret ; --------------------------------------------------------------------------- zloc_515: ; If you get here, then "do not attack next note" was set... ld a,(ix+zTrack.NoteFillMaster) ; Get master "note fill" value or a ; test it jr z,zloc_505 ; If it's zero, then just process normally ld a,(ix+zTrack.NoteFillTimeout) ; Otherwise, get current "note fill" value or a ; Test it jr nz,zloc_505 ; If it's not zero, then just process normally ret ; --------------------------------------------------------------------------- ; zloc_522: zVolEnvHold: ; This just decrements the flutter to keep it in place; no more volume changes in this list if FixDriverBugs dec (ix+zTrack.VolFlutter) dec (ix+zTrack.VolFlutter) ; Put index back (before final volume value) jr zPSGDoVolFX ; Loop back and update volume else ; DANGER! This effectively halts all future volume updates, breaking fades. dec (ix+zTrack.VolFlutter) ; Put index back (before flag 80h) ret ; Return and don't update volume on this frame (!!!) endif ; End of function zPSGDoVolFX ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_526 zPSGNoteOff: bit 2,(ix+zTrack.PlaybackControl) ; Is "SFX override" bit set? ret nz ; If so, quit! ld a,(ix+zTrack.VoiceControl) ; Get "voice control" byte (loads upper bits which specify attenuation setting) ; |a| |1Fh| ; VOL1 0x90 = 100 1xxxx vol 4b xxxx = attenuation value ; VOL2 0xb0 = 101 1xxxx vol 4b ; VOL3 0xd0 = 110 1xxxx vol 4b or 1Fh ; Attenuation Off ld (zPSG),a if FixDriverBugs ; Without zInitMusicPlayback forcefully muting all channels, there's the ; risk of music accidentally playing noise because it can't detect if ; the PSG4/noise channel needs muting, on track initialisation. ; This bug can be heard be playing the End of Level music in CNZ, whose ; music uses the noise channel. S&K's driver contains a fix just like this. cp 0DFh ; Are we stopping PSG3? ret nz ld a,0FFh ; If so, stop noise channel while we're at it ld (zPSG),a ; Stop noise channel endif ret ; End of function zPSGNoteOff ; --------------------------------------------------------------------------- ; lookup table of FM note frequencies for instruments and sound effects if OptimiseDriver ensure1byteoffset 18h else ensure1byteoffset 0C0h endif ; zbyte_534: zFrequencies: dw 025Eh,0284h,02ABh,02D3h,02FEh,032Dh,035Ch,038Fh,03C5h,03FFh,043Ch,047Ch if OptimiseDriver=0 ; We will calculate these, instead, which will save space dw 0A5Eh,0A84h,0AABh,0AD3h,0AFEh,0B2Dh,0B5Ch,0B8Fh,0BC5h,0BFFh,0C3Ch,0C7Ch dw 125Eh,1284h,12ABh,12D3h,12FEh,132Dh,135Ch,138Fh,13C5h,13FFh,143Ch,147Ch dw 1A5Eh,1A84h,1AABh,1AD3h,1AFEh,1B2Dh,1B5Ch,1B8Fh,1BC5h,1BFFh,1C3Ch,1C7Ch dw 225Eh,2284h,22ABh,22D3h,22FEh,232Dh,235Ch,238Fh,23C5h,23FFh,243Ch,247Ch dw 2A5Eh,2A84h,2AABh,2AD3h,2AFEh,2B2Dh,2B5Ch,2B8Fh,2BC5h,2BFFh,2C3Ch,2C7Ch dw 325Eh,3284h,32ABh,32D3h,32FEh,332Dh,335Ch,338Fh,33C5h,33FFh,343Ch,347Ch dw 3A5Eh,3A84h,3AABh,3AD3h,3AFEh,3B2Dh,3B5Ch,3B8Fh,3BC5h,3BFFh,3C3Ch,3C7Ch ; 96 entries endif ;zloc_5F4 zPSGSilenceAll: ld hl,zPSG ; PSG reg ld (hl),9Fh ; Stop channel 0 ld (hl),0BFh ; Stop channel 1 ld (hl),0DFh ; Stop channel 2 ld (hl),0FFh ; Stop noise channel ret ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_600 zPauseMusic: jp m,+ ; If we are to unpause music, branch ld a,(zPaused) ; Get paused flag or a ; Are we paused already? ret nz ; If so, return ld a,0FFh ; a = 0FFh ld (zPaused),a ; Set paused flag call zFMSilenceAll jp zPSGSilenceAll + if OptimiseDriver xor a ; a = 0 ld (zAbsVar.StopMusic),a ; Clear pause/unpause flag else push ix ; Save ix (nothing uses this, beyond this point...) ld (ix+zVar.StopMusic),0 ; Clear pause/unpause flag xor a ; a = 0 endif ld (zPaused),a ; Clear paused flag ld ix,zSongDACFMStart ; ix = pointer to track RAM ld b,MUSIC_DAC_FM_TRACK_COUNT ; 1 DAC + 6 FM call zResumeTrack bankswitch SoundIndex ; Now for SFX ld a,0FFh ; a = 0FFH ld (zDoSFXFlag),a ; Set flag to say we are updating SFX ld ix,zSFX_FMStart ; ix = pointer to SFX track RAM ld b,SFX_FM_TRACK_COUNT ; 3 FM call zResumeTrack xor a ; a = 0 ld (zDoSFXFlag),a ; Clear SFX updating flag if OptimiseDriver=0 call zBankSwitchToMusic ; Back to music (Pointless: music isn't updated until the next frame) pop ix ; Restore ix (nothing uses this, beyond this point...) endif ret ; End of function zPauseMusic ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_64D zResumeTrack: bit 7,(ix+zTrack.PlaybackControl) ; Is track playing? jr z,+ ; Branch if not bit 2,(ix+zTrack.PlaybackControl) ; Is SFX overriding track? jr nz,+ ; Branch if not if OptimiseDriver=0 ; cfSetVoiceCont already does this ld c,(ix+zTrack.AMSFMSPan) ; AMS/FMS/panning flags ld a,(ix+zTrack.VoiceControl) ; Get voice control bits... and 3 ; ... the FM portion of them add a,0B4h ; Command to select AMS/FMS/panning register rst zWriteFMIorII endif push bc ; Save bc ld c,(ix+zTrack.VoiceIndex) ; Current track FM instrument call cfSetVoiceCont pop bc ; Restore bc + ld de,zTrack.len ; de = Track size add ix,de ; Advance to next track djnz zResumeTrack ; loop ret ; End of function zResumeTrack ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_674 zCycleQueue: ld a,(zAbsVar.QueueToPlay) ; Check if a sound request was made zComRange+08h cp 80h ; Is queue slot equal to 80h? ret nz ; If not, return ld hl,zAbsVar.SFXToPlay ; Get address of next sound ld a,(zAbsVar.SFXPriorityVal) ; Get current SFX priority ld c,a ; a -> c ld b,3 ; b = 3 - ld a,(hl) ; Get sound to play -> 'a' ld e,a ; 'a' -> 'e' ld (hl),0 ; Clear it back to zero (we got it) inc hl ; hl = pointer to next queue item cp MusID__First ; Is it before first music? jr c,zlocQueueNext ; if so, branch cp CmdID__First ; Is it a special command? jr nc,zlocQueueItem ; If so, branch sub SndID__First ; Subtract first SFX index jr c,zlocQueueItem ; If it was music, branch add a,zSFXPriority&0FFh ; a = low byte of pointer to SFX priority ld l,a ; l = low byte of pointer to SFX priority adc a,(zSFXPriority&0FF00h)>>8 ; a = low byte of pointer to SFX priority + high byte of same pointer sub l ; a = high byte of pointer to SFX priority ld h,a ; hl = pointer to SFX priority ld a,(hl) ; Get SFX priority cp c ; Is the new SFX of a higher priority? jr c,+ ; Branch if not ld c,a ; Save new priority call zlocQueueItem ; Queue the new SFX + ld a,c ; Get back SFX priority or a ; Is it negative (jumping sound)? ret m ; Return if so ld (zAbsVar.SFXPriorityVal),a ; Store the new priority ret ; --------------------------------------------------------------------------- zlocQueueNext: djnz - ret ; --------------------------------------------------------------------------- zlocQueueItem: ld a,e ; restore a to be the last queue item read ld (zAbsVar.QueueToPlay),a ; Put it as the next item to play ret ; End of function zCycleQueue ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ; zsub_6B2: zPlaySoundByIndex: or a ; is it sound 00? jp z,zClearTrackPlaybackMem ; if yes, branch to RESET EVERYTHING!! if MusID__First-1 == 80h ret p ; return if it was (invalidates 00h-7Fh; maybe we don't want that someday?) else cp MusID__First ret c ; return if id is less than the first music id endif ld (ix+zVar.QueueToPlay),80h ; Rewrite zComRange+8 flag so we know nothing new is coming in cp MusID__End ; is it music (less than index 20)? jp c,zPlayMusic ; if yes, branch to play the music cp SndID__First ; is it not a sound? (this check is redundant if MusID__End == SndID__First...) ret c ; if it isn't a sound, return (do nothing) cp SndID__End ; is it a sound (less than index 71)? jp c,zPlaySound_CheckRing ; if yes, branch to play the sound cp CmdID__First ; is it after the last regular sound but before the first special sound command (between 71 and 78)? ret c ; if yes, return (do nothing) cp MusID_Pause ; is it sound 7E or 7F (pause all or resume all) ret nc ; if yes, return (those get handled elsewhere) ; Otherwise, this is a special command to the music engine... sub CmdID__First ; convert index 78-7D to a lookup into the following jump table add a,a add a,a ld (zloc_6D5+1),a ; store into the instruction after zloc_6D5 (self-modifying code) zloc_6D5: jr $ ; --------------------------------------------------------------------------- zCommandIndex: CmdPtr_StopSFX: jp zStopSoundEffects ; sound test index 78 db 0 CmdPtr_FadeOut: jp zFadeOutMusic ; 79 db 0 CmdPtr_SegaSound: jp zPlaySegaSound ; 7A db 0 CmdPtr_SpeedUp: jp zSpeedUpMusic ; 7B db 0 CmdPtr_SlowDown: jp zSlowDownMusic ; 7C db 0 CmdPtr_Stop: jp zStopSoundAndMusic ; 7D db 0 CmdPtr__End: ; --------------------------------------------------------------------------- ; zloc_6EF: zPlaySegaSound: if FixDriverBugs ; reset panning (don't want Sega sound playing on only one speaker) ld a,0B6h ; Set Panning / AMS / FMS ld c,0C0h ; default Panning / AMS / FMS settings (only stereo L/R enabled) rst zWriteFMII ; Set it! endif ld a,2Bh ; DAC enable/disable register ld c,80h ; Command to enable DAC rst zWriteFMI bankswitch Snd_Sega ; Want Sega sound ld hl,zmake68kPtr(Snd_Sega) ; was: 9E8Ch ld de,(Snd_Sega_End - Snd_Sega)/2 ; was: 30BAh ld a,2Ah ; DAC data register ld (zYM2612_A0),a ; Select it ld c,80h ; If QueueToPlay is not this, stops Sega PCM - ld a,(hl) ; Get next PCM byte ld (zYM2612_D0),a ; Send to DAC inc hl ; Advance pointer nop ld b,0Ch ; Sega PCM pitch djnz $ ; Delay loop nop ld a,(zAbsVar.QueueToPlay) ; Get next item to play cp c ; Is it 80h? jr nz,+ ; If not, stop Sega PCM ld a,(hl) ; Get next PCM byte ld (zYM2612_D0),a ; Send to DAC inc hl ; Advance pointer nop ld b,0Ch ; Sega PCM pitch djnz $ ; Delay loop nop dec de ; 2 less bytes to play ld a,d ; a = d or e ; Is de zero? jp nz,- ; If not, loop + call zBankSwitchToMusic ld a,(zAbsVar.DACEnabled) ; DAC status ld c,a ; c = DAC status ld a,2Bh ; DAC enable/disable register rst zWriteFMI ret ; --------------------------------------------------------------------------- ; zloc_73D: zPlayMusic: if FixDriverBugs=0 ; This is a workaround for a bug, where playing a new song will distort any SFX that were already playing push af call zStopSoundEffects ; Stop all sounds before starting BGM pop af endif ld (zCurSong),a ; Get current BGM cp MusID_ExtraLife ; If NOT 1-up sound... jr nz,zloc_784 ; ... skip over the following code ; The following code disables all sound (technically for duration of 1-up) ld a,(zAbsVar.1upPlaying) ; Check if 1-up sound is already playing or a ; Test it jr nz,zBGMLoad ; If it is, then just reload it! (I suppose a humorous restore-to-1up could happen otherwise... with no good results after that) ld ix,zTracksStart ; Starting at beginning of all tracks... ld de,zTrack.len ; Each track size ld b,MUSIC_TRACK_COUNT ; All 10 (DAC, 6FM, 3PSG) tracks - res 2,(ix+zTrack.PlaybackControl) ; Clear "SFX is overriding" bit (no SFX are allowed!) add ix,de ; Next track djnz - ld ix,zTracksSFXStart ; 'ix' points to start of SFX track memory (10 prior tracks were DAC, 6 FM, 3 PSG) ld b,SFX_TRACK_COUNT ; 6 SFX tracks total (3FM, 3PSG) - res 7,(ix+zTrack.PlaybackControl) ; Clear "is playing" bit! (No SFX allowed!) add ix,de ; Next track djnz - ; This performs a "massive" backup of all of the current track positions ; for restoration after 1-up BGM completes ld de,zTracksSaveStart ; Backup memory address ld hl,zAbsVar ; Starts from zComRange ld bc,zTracksSaveEnd-zTracksSaveStart ; for this many bytes ldir ; Go! ld a,80h ld (zAbsVar.1upPlaying),a ; Set 1-up song playing flag xor a ld (zAbsVar.SFXPriorityVal),a ; Clears SFX priority jr zBGMLoad ; Now load 1-up BGM ; --------------------------------------------------------------------------- zloc_784: xor a ld (zAbsVar.1upPlaying),a ; clear 1-up is playing flag (it isn't) ld (zAbsVar.FadeInCounter),a ; clear fade-in frame count ld (zAbsVar.FadeOutCounter),a ; clear fade-out frame count ;zloc_78E zBGMLoad: call zInitMusicPlayback ld a,(zCurSong) ; So, let's take your desired song, put it into 'a' sub MusID__First ; Make it a zero-based entry ... ld e,a ; Transform 'a' into 16-bit de ld d,0 ld hl,zSpedUpTempoTable ; Load 'hl' of "sped up" tempos [I think] add hl,de ; Offset by 16-bit version of song index to proper tempo ld a,(hl) ; Get value at this location -> 'a' ld (zAbsVar.TempoTurbo),a ; Store 'a' here (provides an alternate tempo or something for speed up mode) ld hl,zMasterPlaylist ; Get address of the zMasterPlaylist add hl,de ; Add the 16-bit offset here ld a,(hl) ; Get "fixed" index ld b,a ; 'a' -> 'b' ; The following instructions enable a bankswitch routine and 80h ; Get only 'bank' bit ld (zAbsVar.MusicBankNumber),a ; Store this (use to enable alternate bank) ld a,b ; Restore 'a' add a,a ; Adding a+a causes a possible overflow and a multiplication by 2 add a,a ; Now multiplied by 4 and another possible overflow ld c,a ; Result -> 'c' ccf ; Invert carry flag... sbc a,a ; ... so that this sets a to FFh if bit 6 of original a was clear (allow PAL double-update), zero otherwise (do not allow PAL double-update) ld (zAbsVar.IsPalFlag),a ; Set IsPalFlag ld a,c ; Put prior multiply result back in add a,a ; Now multiplied by 8! sbc a,a ; This is FFh if bit 5 of original a was set (uncompressed song), zero otherwise (compressed song) push af ; Backing up result...? ld a,b ; Put 80h based index -> 'a' and 1Fh ; Strip the flag bits add a,a ; multiply by 2; now 'a' is offset into music table, save for the $8000 ld e,a ld d,0 ; de = a ld hl,zROMWindow add hl,de ; "hl" now contains 2-byte offset for music address table lookup push hl ; Save 'hl' (will be damaged by bank switch) call zBankSwitchToMusic ; Bank switch to start of music in ROM! pop hl ; Restore 'hl' ld e,(hl) inc hl ld d,(hl) ; Getting offset within bank to music -> de ; If we bypass the Saxman decompressor, the Z80 engine starts ; with the assumption that we're already decompressed with 'de' pointing ; at the decompressed data (which just so happens to be the ROM window) pop af or a ; Was the uncompressed song flag set? jr nz,+ ; Bypass the Saxman decompressor if so ; This begins a call to the Saxman decompressor: ex de,hl exx push hl push de push bc if OptimiseDriver=0 exx endif call zSaxmanDec exx pop bc pop de pop hl exx ld de,zMusicData ; Saxman compressed songs start at zMusicData (1380h) + ; Begin common track init code push de pop ix ; ix = de (BGM's starting address) ld e,(ix+0) ; Get voice table pointer low byte -> 'e' ld d,(ix+1) ; Get voice table pointer high byte -> 'd' ld (zAbsVar.VoiceTblPtr),de ; Set master copy of this value in local memory ld a,(ix+5) ; Get main tempo value ld (zAbsVar.TempoMod),a ; Store it at (zComRange+12h) ld b,a ; tempo -> 'b' ld a,(zAbsVar.SpeedUpFlag) ; Get found speed shoe flag (zComRange+14h) (preloaded before this) or a ; test it ld a,b ; Restore normal song tempo jr z,+ ; if the speed shoe flag was zero, skip this step ld a,(zAbsVar.TempoTurbo) ; Put the corresponding speed shoe tempo for song + ld (zAbsVar.CurrentTempo),a ; Current tempo for TempoWait ld (zAbsVar.TempoTimeout),a ; Tempo accumulator for TempoWait ld a,5 ld (zPALUpdTick),a ; reset PAL update tick to 5 (update immediately) push ix pop hl ; hl = ix (BGM's starting address) ld de,6 add hl,de ; +06h (to DAC pointer) ld a,(ix+2) ; Get number of FM+DAC channels this BGM has or a ; Test it jp z,zloc_884 ; If zero, then don't init any ld b,a ; 'a' -> 'b' (num FM+DAC channels this song, for loop) push iy ; Save 'iy' ld iy,zTracksStart ; 'iy' points to start of track memory ld c,(ix+4) ; Get tempo divider -> 'c' if FixDriverBugs=0 ; The bugfix in zInitMusicPlayback does this, already ld de,zFMDACInitBytes ; 'de' points to zFMDACInitBytes endif - ld (iy+zTrack.PlaybackControl),82h ; Set "track is playing" bit and "track at rest" bit if FixDriverBugs=0 ; The bugfix in zInitMusicPlayback does this, already ld a,(de) ; Get current byte from zFMDACInitBytes -> 'a' inc de ; will get next byte from zFMDACInitBytes next time ld (iy+zTrack.VoiceControl),a ; Store this byte to "voice control" byte endif ld (iy+zTrack.TempoDivider),c ; Store timing divisor from header for this track ld (iy+zTrack.StackPointer),zTrack.GoSubStack ; set "gosub" (coord flag F8h) stack init value (starts at end of this track's memory) ld (iy+zTrack.AMSFMSPan),0C0h ; default Panning / AMS / FMS settings (only stereo L/R enabled) ld (iy+zTrack.DurationTimeout),1 ; set current duration timeout to 1 (should expire next update, play first note, etc.) if FixDriverBugs=0 ; The bugfix in zInitMusicPlayback does this, already push de ; saving zFMDACInitBytes pointer endif push bc ; saving number of channels and tempo divider ('bc' gets needlessly damaged by 'ldi' instructions coming up) ld a,iyl ; current track pointer low byte -> 'a' add a,zTrack.DataPointerLow ld e,a adc a,iyu sub e ld d,a ; de = iy + 3 ('de' is pointing to track offset address) if OptimiseDriver ld bc,4 ldir ; while (bc-- > 0) *de++ = *hl++; (copy track address, default key offset, default volume) else ldi ; *de++ = *hl++ (copy track address low byte from header to track's copy of this value) ldi ; *de++ = *hl++ (copy track address high byte from header to track's copy of this value) ldi ; *de++ = *hl++ (default key offset, typically 0, can be set later by coord flag E9) ldi ; *de++ = *hl++ (track default volume) endif ld de,zTrack.len ; size of all tracks -> 'de' add iy,de ; offset to next track! pop bc ; restore 'bc' (number of channels and tempo divider) if FixDriverBugs=0 ; The bugfix in zInitMusicPlayback does this, already pop de ; restore 'de' (zFMDACInitBytes current pointer) endif djnz - ; loop for all tracks we're init'ing... ; End of FM+DAC track init loop pop iy ; restore 'iy' ld a,(ix+2) ; 'ix' still points to start of BGM; get number of FM+DAC -> 'a' cp 7 ; Does it equal 7? (6 FM channels) jr nz,+ ; If not, skip this next part xor a ; Clear 'a' if OptimiseDriver=0 ld c,a ; c = 0 endif jr zloc_87E ; jump to zloc_87E + ; Silence FM Channel 6 specifically if it's not in use if OptimiseDriver=0 ; A later call to zFMNoteOff does this, already ld a,28h ; Key on/off FM register ld c,6 ; FM channel 6 rst zWriteFMI ; All operators off endif if FixDriverBugs=0 ; The added zFMSilenceChannel does this, already ld a,42h ; Starting at FM Channel 6 Operator 1 Total Level register ld c,0FFh ; Silence value ld b,4 ; Write to all four FM Channel 6 operators ; Set all TL values to silence! - rst zWriteFMII add a,4 ; Next operator djnz - endif ; Panning isn't normally set until zSetVoice. ; This is a problem for the DAC track since it never uses zSetVoice ; (or at least it shouldn't), so we reset the panning here. ld a,0B6h ; Set Panning / AMS / FMS ld c,0C0h ; default Panning / AMS / FMS settings (only stereo L/R enabled) rst zWriteFMII ; Set it! ld a,80h ; FM Channel 6 is NOT in use (will enable DAC) if OptimiseDriver=0 ld c,a ; Set this as value to be used in FM register write coming up... endif zloc_87E: if OptimiseDriver ld c,a endif ld (zAbsVar.DACEnabled),a ; Note whether FM Channel 6 is in use (enables DAC if not) ld a,2Bh ; Set DAC Enable appropriately rst zWriteFMI ; Set it! ; End of DAC/FM init, begin PSG init zloc_884: ld a,(ix+3) ; Get number of PSG tracks or a ; Test it jp z,zloc_8D0 ; If zero, skip this part! ld b,a ; 'a' -> 'b' (num PSG tracks this song, for loop) push iy ; Save 'iy' ld iy,zSongPSG1 ; 'iy' points to start of PSG track memory (7 prior tracks were DAC and 6 FM) ld c,(ix+4) ; Get tempo divider -> 'c' if FixDriverBugs=0 ; The bugfix in zInitMusicPlayback does this, already ld de,zPSGInitBytes ; 'de' points to zPSGInitBytes endif - ld (iy+zTrack.PlaybackControl),82h ; Set "track is playing" bit and "track at rest" bit if FixDriverBugs=0 ; The bugfix in zInitMusicPlayback does this, already ld a,(de) ; Get current byte from zPSGInitBytes -> 'a' inc de ; will get next byte from zPSGInitBytes next time ld (iy+zTrack.VoiceControl),a ; Store this byte to "voice control" byte endif ld (iy+zTrack.TempoDivider),c ; Store timing divisor from header for this track ld (iy+zTrack.StackPointer),zTrack.GoSubStack ; "gosub" stack init value ld (iy+zTrack.DurationTimeout),1 ; set current duration timeout to 1 (should expire next update, play first note, etc.) if FixDriverBugs=0 ; The bugfix in zInitMusicPlayback does this, already push de ; saving zPSGInitBytes pointer endif push bc ; saving number of channels and tempo divider ('bc' gets needlessly damaged by 'ldi' instructions coming up) ld a,iyl ; current track pointer low byte -> 'a' add a,zTrack.DataPointerLow ld e,a adc a,iyu sub e ld d,a ; de = iy + 3 ('de' is pointing to track offset address) if OptimiseDriver ld bc,4 ldir ; while (bc-- > 0) *de++ = *hl++; (copy track address, default key offset, default volume) else ldi ; *de++ = *hl++ (copy track address low byte from header to track's copy of this value) ldi ; *de++ = *hl++ (copy track address high byte from header to track's copy of this value) ldi ; *de++ = *hl++ (default key offset, typically 0, can be set later by coord flag E9) ldi ; *de++ = *hl++ (track default volume) endif inc hl ; Get default PSG tone ld a,(hl) ; -> 'a' inc hl ; This byte is usually the same as the prior, unused ld (iy+zTrack.VoiceIndex),a ; Store current PSG tone ld de,zTrack.len ; size of all tracks -> 'de' add iy,de ; offset to next track! pop bc ; restore 'bc' (number of channels and tempo divider) if FixDriverBugs=0 ; The bugfix in zInitMusicPlayback does this, already pop de ; restore 'de' (zPSGInitBytes current pointer) endif djnz - ; loop for all tracks we're init'ing... pop iy ; restore 'iy' ; End of PSG tracks init, begin SFX tracks init zloc_8D0: ld ix,zTracksSFXStart ; 'ix' points to start of SFX track memory (10 prior tracks were DAC, 6 FM, 3 PSG) ld b,SFX_TRACK_COUNT ; 6 SFX tracks total (3FM, 3PSG) ld de,zTrack.len ; size between tracks zloc_8D9: bit 7,(ix+zTrack.PlaybackControl) ; Is this track currently playing? jr z,zloc_8FB ; If not, jump to zloc_8FB (no work to do!) ld a,(ix+zTrack.VoiceControl) ; Get "voice control" byte... or a ; Test it jp m,+ ; If this is a PSG track, jump to '+' sub 2 ; Otherwise, subtract 2... add a,a ; ... multiply by 2 (preparing to index starting from FM 3 only) jr zloc_8F1 ; Jump to zloc_8F1 (general track setup) + rra rra rra rra and 0Fh ; for PSG, just shift it down by 4 and we have its index! zloc_8F1: add a,zMusicTrackOffs&0FFh ; get offset into appropriate music track... ld (zloc_8F6+1),a ; store into the instruction after zloc_8F6 (self-modifying code) zloc_8F6: ld hl,(zMusicTrackOffs) ; This loads address of corresponding MUSIC track (the track that this SFX track would normally play over) if FixDriverBugs set 2,(hl) ; Set the "SFX override" bit else res 2,(hl) ; Clear the "SFX override" bit (Why??? According to S1's driver, this should be a 'set') endif zloc_8FB: add ix,de ; Next track.. djnz zloc_8D9 ; Loop for all tracks ; End of SFX tracks init... ld ix,zSongFM1 ; 'ix' points to first FM music track ld b,MUSIC_FM_TRACK_COUNT ; For all 6 of those... if FixDriverBugs ; zFMNoteOff isn't enough to silence the entire channel: ; For added measure, we set Total Level and Release Rate, too. - push bc bit 2,(ix+zTrack.PlaybackControl) ; Is bit 2 (SFX overriding) set? call z,zFMSilenceChannel ; If not, branch add ix,de ; Next track pop bc djnz - else - call zFMNoteOff ; Send Key Off add ix,de ; Next track djnz - endif ld b,MUSIC_PSG_TRACK_COUNT ; For all 3 PSG tracks... - call zPSGNoteOff ; Send Note Off add ix,de ; Next track djnz - ret if FixDriverBugs zFMSilenceChannel: call zSetMaxRelRate ld a,(ix+zTrack.VoiceControl) ; Get voice control byte and 3 ; Channels only! add a,40h ; Set total level... ld c,7Fh ; ... to minimum envelope amplitude... call zFMOperatorWriteLoop ; ... for all operators of this track's channel jp zFMNoteOff zSetMaxRelRate: ld a,(ix+zTrack.VoiceControl) ; Get voice control byte and 3 ; Channels only! add a,80h ; Add register 80, set D1L to minimum and RR to maximum... ld c,0FFh ; ... for all operators on this track's channel zFMOperatorWriteLoop: ld b,4 ; Loop 4 times .loop: rst zWriteFMIorII ; Write to part I or II, as appropriate add a,4 ; a += 4 djnz .loop ; Loop ret endif ; --------------------------------------------------------------------------- ; FM channel assignment bits ;zbyte_916 zFMDACInitBytes: db 6, 0, 1, 2, 4, 5, 6 ; first byte is for DAC; then notice the 0, 1, 2 then 4, 5, 6; this is the gap between parts I and II for YM2612 port writes ; Default values for PSG tracks ;zbyte_91D zPSGInitBytes: db 80h,0A0h,0C0h ; Specifically, these configure writes to the PSG port for each channel ; zloc_920: zPlaySound_CheckRing: ld c,a ; Store sound index -> 'c' ld a,(ix+zVar.1upPlaying) ; Get "is 1-up playing" flag... or (ix+zVar.FadeInFlag) ; Or it with fading in flag jp nz,zloc_KillSFXPrio ; If either is set, SFX cannot be played!! xor a ld (zSpindashActiveFlag),a ; Clear spindash sound flag ld a,c ; Sound index -> 'a' cp SndID_Ring ; is this the ring sound? jr nz,zPlaySound_CheckGloop ; if not, branch ; This is the ring sound... ld a,(zRingSpeaker) ; 0 plays left, FFh plays right or a ; Test it jr nz,+ ; If it's not zero, we skip this next step ld c,SndID_RingLeft ; do something different (probably speaker change)... + cpl ; If it was 0, it's now FFh, or vice versa ld (zRingSpeaker),a ; Store new ring speaker value (other side) jp zPlaySound ; now play the play the ring sound ; --------------------------------------------------------------------------- ; zloc_942: zPlaySound_CheckGloop: if OptimiseDriver=0 ld a,c endif cp SndID_Gloop ; is this the bloop/gloop noise? jr nz,zPlaySound_CheckSpindash ; if not, branch ld a,(zGloopFlag) cpl ld (zGloopFlag),a or a ret z ; sometimes don't play it jp zPlaySound ; now play the gloop sound ; --------------------------------------------------------------------------- ; zloc_953: zPlaySound_CheckSpindash: if OptimiseDriver=0 ld a,c endif cp SndID_SpindashRev ; is this the spindash rev sound playing? jr nz,zPlaySound ; if not, branch ld a,(zSpindashPlayingCounter) or a ld a,(zSpindashExtraFrequencyIndex) jr nz,+ ; if the spindash sound is already playing, branch ld a,-1 ; reset the extra frequency (becomes 0 on the next line) + inc a ; increase the frequency cp 0Ch jr nc,+ ld (zSpindashExtraFrequencyIndex),a + ld a,3Ch ld (zSpindashPlayingCounter),a ld a,-1 ld (zSpindashActiveFlag),a ; zloc_975: zPlaySound: bankswitch SoundIndex ; Switch to SFX banks ld hl,zmake68kPtr(SoundIndex) ; 'hl' points to beginning of SFX bank in ROM window ld a,c ; 'c' -> 'a' sub SndID__First ; Bring 'a' down to index value add a,a ; Multiply it by 2 ld e,a ld d,0 ; de = a add hl,de ; now hl points to a pointer in the SoundIndex list (such as rom_ptr_z80 Sound20) ld a,(hl) inc hl ld h,(hl) ld l,a ; now hl points to a sound's data (such as Sound20: ...) ld e,(hl) inc hl ld d,(hl) ; 'de' points to custom voice table (if any; otherwise is 0000h) inc hl ld (zloc_A26+1),de ; store into the instruction after zloc_A26 (self-modifying code) ld c,(hl) ; Timing divisor -> 'c' inc hl ld b,(hl) ; Total channels used -> 'b' inc hl zloc_99F: push bc ; backup divisor/channel usage xor a ; a = 0 (will end up being NO CUSTOM VOICE TABLE!) ld (zloc_A1D+1),a ; store into the instruction after zloc_A1D (self-modifying code) (Kind of pointless, always sets it to zero... maybe PSG would've had custom "flutter" tables?) push hl ; save current position within sound (offset 04h) inc hl ; next byte... ld a,(hl) ; Track sound def -> 'a' (if 80h set, it's PSG, otherwise it's FM) -- note this also tells what channel it's on (80, A0, C0 for PSG, FM channel assignments otherwise) or a ; test it jp m,+ ; if bit 7 (80h) set (meaning PSG track), skip next part... sub 2 ; Subtract 2 from this value add a,a ; Multiply it by 2 jp zloc_9CA ; This is an FM sound track... + ; This is a PSG track! ; Always ends up writing zero to voice table pointer? ld (zloc_A1D+1),a ; store into the instruction after zloc_A1D (self-modifying code) cp 0C0h ; Is this PSG3? jr nz,+ ; If not, skip this part push af or 1Fh ; Set silence on PSG! ld (zPSG),a xor 20h ld (zPSG),a pop af + rra rra rra rra and 0Fh ; for PSG, just shift it down by 4 and we have its index! zloc_9CA: add a,zMusicTrackOffs&0FFh ; Offset to corresponding music track ld (zloc_9CF+1),a ; store into the instruction after zloc_9CF (self-modifying code) zloc_9CF: ld hl,(zMusicTrackOffs) ; 'hl' is now start of corresponding music track set 2,(hl) ; Set "SFX is overriding this track!" bit add a,zSFXTrackOffs-zMusicTrackOffs ; Jump to corresponding SFX track ld (zloc_9D9+2),a ; store into the instruction after zloc_9D9 (self-modifying code) zloc_9D9: ld ix,(zSFXTrackOffs) ; 'ix' is now start of corresponding SFX track ; Little bit busy there, but basically for a given 'a' value, where a == 0 ; means first SFX track (FM3), 'hl' now points to the music track and 'ix' points ; to the SFX track that both correspond to track 'a' ; Now we're going to clear this SFX track... ld e,ixl ld d,ixu ; de = ix push de ; save 'de' ld l,e ; hl = de (start of SFX track) ld h,d ld (hl),0 ; store 00h on first byte of track inc de ; next byte... ld bc,zTrack.len-1 ; For all bytes in the track, minus 1 (since we're copying 00h from first byte) ldir ; Clear track memory! pop de ; Restore 'de' (start of SFX track yet again) pop hl ; Get 'hl' back from way before (offset of sound in ROM + 04h) ; ld a,e ; add a,zTrack.PlaybackControl ; ld e,a ; adc a,d ; sub e ; ld d,a ldi ; *de++ = *hl++ (write playback control byte) (... not really sure why this is used) ldi ; *de++ = *hl++ (write voice control byte) (sets whether is PSG or what) pop bc ; restore 'bc'... push bc ; ... Um, back it up again! ld (ix+zTrack.TempoDivider),c ; Set timing divisor of SFX track ld (ix+zTrack.DurationTimeout),1 ; current duration timeout to 1 (will expire immediately and thus update) ld (ix+zTrack.StackPointer),zTrack.GoSubStack ; Reset track "gosub" stack ld a,e add a,zTrack.DataPointerLow-zTrack.TempoDivider ld e,a adc a,d sub e ld d,a ; de += 1 (skip timing divisor; already set) if OptimiseDriver ld bc,3 ldir ; while (bc-- > 0) *de++ = *hl++; (copy track address, default key offset) else ldi ; *de++ = *hl++ (track position low byte) ldi ; *de++ = *hl++ (track position high byte) ldi ; *de++ = *hl++ (key offset) endif ; If spindash active, the following block updates its frequency specially: ld a,(zSpindashActiveFlag) or a jr z,+ ; If spindash not last sound played, skip this ld a,(zSpindashExtraFrequencyIndex) ; Get current frequency index dec de ; Go back to key offset ex de,hl ; hl <=> de add a,(hl) ; Add spindash key offset! ex de,hl ; de <=> hl (just done because we wanted add a,(hl)) ld (de),a ; Store it! inc de ; Go passed key offset again + ldi ; *de++ = *hl++ (channel volume) zloc_A1D: ; Modified way back within zloc_99F ld a,0 ; "self-modified code"; if 00h, no custom voice table defined for this track or a ; Test it jr nz,+ ; If not zero, skip next part... ld (ix+zTrack.AMSFMSPan),0C0h ; Default panning / AMS / FMS settings (just L/R Stereo enabled) zloc_A26: ld de,0 ; "self-modified code" ; This will be modified to custom voice table address (possibly still 0000h) ld (ix+zTrack.VoicePtrLow),e ; low byte of custom voice table (for SFX) ld (ix+zTrack.VoicePtrHigh),d ; high byte of custom voice table (for SFX) + pop bc ; restore divisor (c) and channel counts (b0) dec b ; One less FM channel jp nz,zloc_99F ; If more to go, loop! jp zBankSwitchToMusic ; Otherwise, prepare to do music... ; --------------------------------------------------------------------------- zloc_KillSFXPrio: xor a ld (zAbsVar.SFXPriorityVal),a ; Reset SFX priority ret ; End of function zPlaySoundByIndex ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ; zsub_A3C: zStopSoundEffects: xor a ld (zAbsVar.SFXPriorityVal),a ; Reset SFX priority ld ix,zTracksSFXStart ; 'ix' points to start of SFX track memory (10 prior tracks were DAC, 6 FM, 3 PSG) ld b,SFX_TRACK_COUNT ; All 6 SFX tracks... zloc_A46: push bc ; Save 'bc' bit 7,(ix+zTrack.PlaybackControl) ; Check if this track was playing jp z,zloc_AB6 ; If not res 7,(ix+zTrack.PlaybackControl) ; You're not playing anymore! res 4,(ix+zTrack.PlaybackControl) ; Not not attacking, either ld a,(ix+zTrack.VoiceControl) ; Get "voice control" byte or a ; Test it jp m,zloc_A89 ; If 80h set (PSG Track) jump to zloc_A89 push af call zFMNoteOff ; FM Key off pop af push ix sub 2 ; Determine proper corresponding music track (starting on FM3, so subtract 2 from channel assignment) add a,a ; Multiply by 2 (each index 2 bytes) add a,zMusicTrackOffs&0FFh ; Get offset -> 'a' ld (zloc_A6C+2),a ; store into the instruction after zloc_A6C (self-modifying code) zloc_A6C: ld ix,(zMusicTrackOffs) ; "self-modified code"; will load appropriate corresponding music track address bit 2,(ix+zTrack.PlaybackControl) ; Was this music track is overridden by an SFX track? jr z,+ ; If not, do nothing res 2,(ix+zTrack.PlaybackControl) ; Otherwise, tell it is is no longer! set 1,(ix+zTrack.PlaybackControl) ; Set track to rest ld a,(ix+zTrack.VoiceIndex) ; Get current voice call zSetVoiceMusic ; Reset FM voice + pop ix jp zloc_AB6 ; jump down to loop ; --------------------------------------------------------------------------- zloc_A89: push af call zPSGNoteOff ; PSG Note off pop af push ix rra rra rra rra and 0Fh ; 'a' is now 08, 0A, 0C, or 0E add a,zMusicTrackOffs&0FFh ld (zloc_A9B+2),a ; store into the instruction after zloc_A9B (self-modifying code) zloc_A9B: ld ix,(zMusicTrackOffs) ; self-modified code from just above; 'ix' points to corresponding Music PSG track res 2,(ix+zTrack.PlaybackControl) ; tell this track it is is no longer overridden by SFX! set 1,(ix+zTrack.PlaybackControl) ; Set track to rest ld a,(ix+zTrack.VoiceControl) ; Get voice control cp 0E0h ; Is this a PSG 3 noise (not tone) track? jr nz,+ ; If it isn't, don't do next part (non-PSG Noise doesn't restore) ld a,(ix+zTrack.PSGNoise) ; Get PSG noise setting ld (zPSG),a ; Write it to PSG + pop ix zloc_AB6: ld de,zTrack.len add ix,de ; Got to next track pop bc ; Restore 'bc' djnz zloc_A46 ; Loop around... ret ; End of function zStopSoundEffects ; --------------------------------------------------------------------------- ; zloc_ABF: zFadeOutMusic: ld a,3 ld (zAbsVar.FadeOutDelay),a ; Set delay ticker to 3 ld a,28h ld (zAbsVar.FadeOutCounter),a ; Set total frames to decrease volume over xor a ld (zSongDAC.PlaybackControl),a ; Stop DAC track (can't fade it) ld (zAbsVar.SpeedUpFlag),a ; No speed shoe tempo? ret ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_AD1 zUpdateFadeout: ld a,(zAbsVar.FadeOutDelay) ; Get current tick count before next volume decrease or a jr z,+ ; If not yet zero... dec (ix+zVar.FadeOutDelay) ; Just decrement it ret + dec (ix+zVar.FadeOutCounter) ; Otherwise, decrement fadeout! jp z,zClearTrackPlaybackMem ; If it hits zero, clear everything! ld (ix+zVar.FadeOutDelay),3 ; Otherwise, reload tick count with 3 push ix ld ix,zSongFM1 ; 'ix' points to first FM music track ld b,MUSIC_FM_TRACK_COUNT ; 6 FM tracks to follow... zloc_AED: bit 7,(ix+zTrack.PlaybackControl) ; Is this track playing? jr z,zloc_B04 ; If not, do nothing inc (ix+zTrack.Volume) ; increment channel volume (remember -- higher is quieter!) jp p,+ ; don't let it overflow res 7,(ix+zTrack.PlaybackControl) ; otherwise, stop playing this track jr zloc_B04 ; just loop + push bc call zSetChanVol ; need to update volume pop bc zloc_B04: ld de,zTrack.len add ix,de ; Next track djnz zloc_AED ; Keep going for all FM tracks... ld b,MUSIC_PSG_TRACK_COUNT ; 3 PSG tracks to follow... zloc_B0D: bit 7,(ix+zTrack.PlaybackControl) ; Is this track playing? jr z,zloc_B2C ; If not, do nothing inc (ix+zTrack.Volume) ; increment channel volume (remember -- higher is quieter!) ld a,10h cp (ix+zTrack.Volume) ; don't let volume go over 0Fh on PSG tracks! jp nc,+ res 7,(ix+zTrack.PlaybackControl) ; Otherwise, stop playing this track jr zloc_B2C + push bc ld b,(ix+zTrack.Volume) ; Channel volume -> 'b' if FixDriverBugs ld a,(ix+zTrack.VoiceIndex) or a ; Is this track using volume envelope 0 (no envelope)? call z,zPSGUpdateVol ; If so, update volume (this code is only run on envelope 1+, so we need to do it here for envelope 0) else ; DANGER! This code ignores volume envelopes, breaking fade on envelope-using tracks. ; (It's also a part of the envelope-processing code, so calling it here is redundant) ; This is only useful for envelope 0 (no envelope). call zPSGUpdateVol ; Update volume (ignores current envelope!!!) endif pop bc zloc_B2C: ld de,zTrack.len add ix,de ; Next track djnz zloc_B0D ; Keep going for all PSG tracks... pop ix ret ; End of function zUpdateFadeout ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_B36 zFMSilenceAll: ld a,28h ; Start at FM KEY ON/OFF register ld b,3 ; Three key on/off per part - ld c,b ; Current key off -> 'c' dec c ; c-- rst zWriteFMI ; Write key off for part I set 2,c ; Set part II select rst zWriteFMI ; Write key off for part II djnz - ld a,30h ; Starting at FM register 30h... ld c,0FFh ; Write dummy kill-all values ld b,60h ; ... up to register 90h - rst zWriteFMI ; ... on part I rst zWriteFMII ; ... and part II inc a ; Next register! djnz - ret ; End of function zFMSilenceAll ; --------------------------------------------------------------------------- ; zloc_B4E: zStopSoundAndMusic: xor a ld (zAbsVar.StopMusic),a ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_B52 zClearTrackPlaybackMem: ; This totally wipes out the track memory and resets playback hardware ld a,2Bh ; DAC Enable register ld c,80h ; Enable DAC rst zWriteFMI ; Write it! ld a,c ; 80h -> 'a' ld (zAbsVar.DACEnabled),a ; Store that to DAC Enabled byte ld a,27h ; Channel 3 special settings ld c,0 ; All clear rst zWriteFMI ; Write it! ; This performs a full clear across all track/playback memory ld hl,zAbsVar ld de,zAbsVar+1 ld (hl),0 ; Starting byte is 00h ld bc,(zTracksSFXEnd-zAbsVar)-1 ; For 695 bytes... ldir ; 695 bytes of clearing! (Because it will keep copying the byte prior to the byte after; thus 00h repeatedly) ld a,80h ld (zAbsVar.QueueToPlay),a ; Nothing is queued call zFMSilenceAll ; Silence FM jp zPSGSilenceAll ; Silence PSG ; End of function zClearTrackPlaybackMem ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_B78 zInitMusicPlayback: ; This function saves some of the queue/flag items and ; otherwise resets all music-related playback memory and ; silences the hardware. Used prior to playing a new song. ; Very similar to zClearTrackPlaybackMem except that it is ; specific to the music tracks... ; Save some queues/flags: ld ix,zAbsVar ld b,(ix+zVar.SFXPriorityVal) ld c,(ix+zVar.1upPlaying) ; 1-up playing flag push bc ld b,(ix+zVar.SpeedUpFlag) ; speed shoe flag ld c,(ix+zVar.FadeInCounter) ; fade in frames push bc ld b,(ix+zVar.SFXToPlay) ; SFX queue slot ld c,(ix+zVar.SFXStereoToPlay) ; Stereo SFX queue slot push bc ; The following clears all playback memory and non-SFX tracks ld hl,zAbsVar ld de,zAbsVar+1 ld (hl),0 ld bc,(zTracksEnd-zAbsVar)-1 ; this many bytes (from start of zComRange to just short of end of PSG3 music track) ldir ; Restore those queue/flags: pop bc ld (ix+zVar.SFXToPlay),b ; SFX queue slot ld (ix+zVar.SFXStereoToPlay),c ; Stereo SFX queue slot pop bc ld (ix+zVar.SpeedUpFlag),b ; speed shoe flag ld (ix+zVar.FadeInCounter),c ; fade in frames pop bc ld (ix+zVar.SFXPriorityVal),b ld (ix+zVar.1upPlaying),c ; 1-up playing flag ld a,80h ld (zAbsVar.QueueToPlay),a if FixDriverBugs ; If a music file's header doesn't define each and every channel, they ; won't be silenced by zloc_8FB, because their tracks aren't properly ; initialised. This can cause hanging notes. So, we'll set them up ; properly here. ld ix,zTracksStart ; Start at the first music track... ld b,MUSIC_TRACK_COUNT ; ...and continue to the last ld de,zTrack.len ld hl,zFMDACInitBytes ; This continues into zPSGInitBytes - ld a,(hl) inc hl ld (ix+zTrack.VoiceControl),a ; Set channel type while we're at it, so subroutines understand what the track is add ix,de ; Next track djnz - ; loop for all channels ret else ; This silences all channels, even those being used by SFX! ; zloc_8FB does the same thing, only better (it doesn't affect SFX channels) call zFMSilenceAll jp zPSGSilenceAll endif ; End of function zInitMusicPlayback ; --------------------------------------------------------------------------- ; zloc_BBE: ; increases the tempo of the music zSpeedUpMusic: ld b,80h ld a,(zAbsVar.1upPlaying) or a ld a,(zAbsVar.TempoTurbo) jr z,zSetTempo jr zSetTempo_1up ; =========================================================================== ; zloc_BCB: ; returns the music tempo to normal zSlowDownMusic: ld b,0 ld a,(zAbsVar.1upPlaying) or a ld a,(zAbsVar.TempoMod) jr z,zSetTempo jr zSetTempo_1up ; =========================================================================== ; helper routines for changing the tempo zSetTempo: ld (zAbsVar.CurrentTempo),a ; Store new tempo value ld a,b ld (zAbsVar.SpeedUpFlag),a ret ; --------------------------------------------------------------------------- ;zloc_BE0 zSetTempo_1up: ld (zSaveVar.CurrentTempo),a ; Store new tempo value ld a,b ld (zSaveVar.SpeedUpFlag),a ret ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_BE8 zUpdateFadeIn: ld a,(zAbsVar.FadeInDelay) ; Get current tick count before next volume increase or a jr z,+ ; If not yet zero... dec (ix+zVar.FadeInDelay) ; Just decrement it ret + ld a,(zAbsVar.FadeInCounter) ; Get current fade out frame count or a jr nz,+ ; If fadeout hasn't reached zero yet, skip this ld a,(zSongDAC.PlaybackControl) ; Get DAC's playback control byte and 0FBh ; Clear "SFX is overriding" bit ld (zSongDAC.PlaybackControl),a ; Set that xor a ld (zAbsVar.FadeInFlag),a ; Done fading-in, SFX can play now ret + dec (ix+zVar.FadeInCounter) ; Otherwise, we decrement fadein! ld (ix+zVar.FadeInDelay),2 ; Otherwise, reload tick count with 2 (little faster than fadeout) push ix ld ix,zSongFM1 ; 'ix' points to first FM music track ld b,MUSIC_FM_TRACK_COUNT ; 6 FM tracks to follow... - bit 7,(ix+zTrack.PlaybackControl) ; Is this track playing? jr z,+ ; If not, do nothing dec (ix+zTrack.Volume) ; decrement channel volume (remember -- lower is louder!) push bc call zSetChanVol ; need to update volume pop bc + ld de,zTrack.len add ix,de ; Next track djnz - ; Keep going for all FM tracks... ld b,MUSIC_PSG_TRACK_COUNT ; 3 PSG tracks to follow... - bit 7,(ix+zTrack.PlaybackControl) ; Is this track playing? jr z,+ ; If not, do nothing dec (ix+zTrack.Volume) ; decrement channel volume (remember -- lower is louder!) push bc ld b,(ix+zTrack.Volume) ; Channel volume -> 'b' if FixDriverBugs ld a,(ix+zTrack.VoiceIndex) or a ; Is this track using volume envelope 0 (no envelope)? call z,zPSGUpdateVol ; If so, update volume (this code is only run on envelope 1+, so we need to do it here for envelope 0) else ; DANGER! This code ignores volume envelopes, breaking fade on envelope-using tracks. ; (It's also a part of the envelope-processing code, so calling it here is redundant) ; This is only useful for envelope 0 (no envelope). call zPSGUpdateVol ; Update volume (ignores current envelope!!!) endif pop bc + ld de,zTrack.len add ix,de ; Next track djnz - ; Keep going for all PSG tracks... pop ix ret ; End of function zUpdateFadeIn ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_C46 zFMNoteOn: ld a,(ix+zTrack.PlaybackControl) ; Get playback control byte and 6 ret nz ; If either bit 1 ("track in rest") and 2 ("SFX overriding this track"), quit! ld a,(ix+zTrack.VoiceControl) ; Get "voice control" byte or 0F0h ; Turn on ALL operators ld c,a ; Set as data to write to FM ld a,28h ; Write to KEY ON/OFF port (key ON in this case) rst zWriteFMI ; do it! ret ; End of function zFMNoteOn ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_C56 zFMNoteOff: ld a,(ix+zTrack.PlaybackControl) ; Load this track's playback control byte and 14h ; Are bits 4 (no attack) or 2 (SFX overriding) set? ret nz ; If they are, return ld a,28h ; Otherwise, send a KEY ON/OFF ld c,(ix+zTrack.VoiceControl) ; Track's data for this key operation ; Format of key on/off: ; 4321 .ccc ; Where 4321 are the bits for which operator, ; and ccc is which channel (0-2 for channels 1-3, 4-6 for channels 4-6 WATCH BIT GAP) rst zWriteFMI ; Write to part I (Note this particular register is ALWAYS sent to part I) ret ; End of function zFMNoteOff ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ; performs a bank switch to where the music for the current track is at ; (there are two possible bank locations for music) ; zsub_C63: zBankSwitchToMusic: ld a,(zAbsVar.MusicBankNumber) or a jr nz,+ bankswitch MusicPoint1 ret + bankswitch MusicPoint2 ret ; End of function zBankSwitchToMusic ; --------------------------------------------------------------------------- ;zloc_C89 zCoordFlag: sub 0E0h if OptimiseDriver ld c,a add a,a add a,c else add a,a add a,a endif ld (coordflagLookup+1),a ; store into the instruction after coordflagLookup (self-modifying code) ld a,(hl) inc hl ; This is the lookup for Coordination flag routines ;zloc_C92 coordflagLookup: jr $ ; --------------------------------------------------------------------------- jp cfPanningAMSFMS ; E0 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfDetune ; E1 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfSetCommunication ; E2 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfJumpReturn ; E3 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfFadeInToPrevious ; E4 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfSetTempoDivider ; E5 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfChangeFMVolume ; E6 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfPreventAttack ; E7 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfNoteFill ; E8 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfChangeTransposition ; E9 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfSetTempo ; EA if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfSetTempoMod ; EB if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfChangePSGVolume ; EC if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfClearPush ; ED if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfStopSpecialFM4 ; EE if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfSetVoice ; EF if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfModulation ; F0 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfEnableModulation ; F1 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfStopTrack ; F2 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfSetPSGNoise ; F3 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfDisableModulation ; F4 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfSetPSGTone ; F5 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfJumpTo ; F6 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfRepeatAtPos ; F7 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfJumpToGosub ; F8 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- jp cfOpF9 ; F9 if OptimiseDriver=0 db 0 endif ; --------------------------------------------------------------------------- ; (via Saxman's doc): panning, AMS, FMS ;zloc_CFC cfPanningAMSFMS: ;Panning, AMS, FMS ;* xx - Value (reg a) ; o Bit 7 - Left channel status ; o Bit 6 - Right channel Status ; o Bit 5-3 - AMS ; o Bit 2 - 0 ; o Bit 1-0 - FMS ; Subject to verification, but even though you COULD set ; AMS/FMS values, it does not appear that's what they intended ; here; instead it appears they only meant for panning control. ; I say this because it retains prior AMS/FMS settings ("and 37h") bit 7,(ix+zTrack.VoiceControl) ; a PSG track ret m ; If so, quit! if FixDriverBugs=0 ; This check is in the wrong place. ; If this flag is triggered by a music track while it's being overridden ; by an SFX, it will use the old panning when the SFX ends. ; This is because zTrack.AMSFMSPan doesn't get updated. bit 2,(ix+zTrack.PlaybackControl) ; If "SFX overriding" bit set... ret nz ; return endif ld c,a ; input val 'a' -> c ld a,(ix+zTrack.AMSFMSPan) ; old PAF value and 37h ; retains bits 0-2, 3-4? or c ; OR'd with new settings ld (ix+zTrack.AMSFMSPan),a ; new PAF value if FixDriverBugs ; The check should only stop hardware access, like this. bit 2,(ix+zTrack.PlaybackControl) ; If "SFX overriding" bit set... ret nz ; return endif ld c,a ; a -> c (YM2612 data write) ld a,(ix+zTrack.VoiceControl) ; Get voice control byte and 3 ; Channels only! add a,0B4h ; Add register B4, stereo output control and LFO sensitivity rst zWriteFMIorII ; depends on bit 2 of (ix+zTrack.VoiceControl) ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): Alter note values by xx ; More or less a pitch bend; this is applied to the frequency as a signed value ;zloc_D1A cfAlterNotesUNK cfAlterNotes: cfDetune: ld (ix+zTrack.Detune),a ; set new detune value ret ; --------------------------------------------------------------------------- ; Set otherwise unused communication byte to parameter ; Used for triggering a boss' attacks in Ristar ;zloc_D1E cfUnknown1 cfSetCommunication: ld (zAbsVar.Communication),a ret ; --------------------------------------------------------------------------- ; Return (Sonic 1 & 2) ;zloc_D22 cfJumpReturn: ld c,(ix+zTrack.StackPointer) ; Get current stack offset -> 'c' ld b,0 ; b = 0 push ix pop hl ; hl = ix add hl,bc ; hl += bc (latest item on "gosub" stack) ld a,(hl) inc hl ld h,(hl) ld l,a ; hl = address from "gosub" stack inc c inc c ld (ix+zTrack.StackPointer),c ; add 2 to "gosub" stack offset (pop) ret ; --------------------------------------------------------------------------- ; Fade-in to previous song (needed on DAC channel, Sonic 1 & 2) ;zloc_D35 cfFadeInToPrevious: ; This performs a "massive" restoration of all of the current ; track positions as they were prior to 1-up BGM ld hl,zTracksSaveStart ; Backup memory address ld de,zAbsVar ; Ends at zComRange ld bc,zTracksSaveEnd-zTracksSaveStart ; for this many bytes ldir ; Go! call zBankSwitchToMusic ld a,(zSongDAC.PlaybackControl) ; Get DAC's playback bit or 4 ld (zSongDAC.PlaybackControl),a ; Set "SFX is overriding" on it (not normal, but will work for this purpose) ld a,(zAbsVar.FadeInCounter) ; Get current count of many frames to continue bringing volume up ld c,a ld a,28h sub c ; a = 28h - c (don't overlap fade-ins?) ld c,a ; 'a' -> 'c' ld b,MUSIC_FM_TRACK_COUNT ; 6 FM tracks to follow... ld ix,zSongFM1 ; 'ix' points to first FM music track - bit 7,(ix+zTrack.PlaybackControl) ; Is this track playing? jr z,+ ; If not, do nothing set 1,(ix+zTrack.PlaybackControl) ; Mark track at rest ld a,(ix+zTrack.Volume) ; Get channel volume add a,c ; Apply current fade value ld (ix+zTrack.Volume),a ; Store it back if OptimiseDriver=0 ; This bit is always cleared (see zPlayMusic) bit 2,(ix+zTrack.PlaybackControl) ; Is track being overridden by SFX? jr nz,+ ; If so, skip next part endif push bc ld a,(ix+zTrack.VoiceIndex) ; Get voice call zSetVoiceMusic ; Update voice (and set volume) pop bc + ld de,zTrack.len add ix,de ; Next track djnz - ; Keep going for all FM tracks... ld b,MUSIC_PSG_TRACK_COUNT ; 3 PSG tracks to follow... - bit 7,(ix+zTrack.PlaybackControl) ; Is this track playing? jr z,+ ; If not, do nothing set 1,(ix+zTrack.PlaybackControl) ; Set track at rest call zPSGNoteOff ; Shut off PSG ld a,(ix+zTrack.Volume) ; Get channel volume add a,c ; Apply current fade value ld (ix+zTrack.Volume),a ; Store it back if FixDriverBugs ; Restore PSG noise type ld a,(ix+zTrack.VoiceControl) cp 0E0h ; Is this the Noise Channel? jr nz,+ ; If not, branch ld a,(ix+zTrack.PSGNoise) ld (zPSG),a ; Restore Noise setting endif + ld de,zTrack.len add ix,de ; Next track djnz - ; Keep going for all FM tracks... ld a,80h ld (zAbsVar.FadeInFlag),a ; Stop any SFX during fade-in ld a,28h ld (zAbsVar.FadeInCounter),a ; Fade in for 28h frames xor a ld (zAbsVar.1upPlaying),a ; Set to zero; 1-up ain't playin' no more ld a,(zAbsVar.DACEnabled) ; DAC not yet enabled... ld c,a ld a,2Bh rst zWriteFMI ; Tell hardware his DAC ain't enabled yet either pop bc pop bc pop bc ; These screw with the return address to make sure DAC doesn't run any further jp zUpdateDAC ; But we update DAC regardless ; --------------------------------------------------------------------------- ; Change tempo divider to xx ;zloc_DB7 cfSetTempoDivider: ld (ix+zTrack.TempoDivider),a ; Set tempo divider on this track only ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): Change channel volume BY xx; xx is signed ;zloc_DBB cfSetVolume cfChangeFMVolume: add a,(ix+zTrack.Volume) ; Add to current volume ld (ix+zTrack.Volume),a ; Update volume jp zSetChanVol ; Immediately set this new volume ; --------------------------------------------------------------------------- ; (via Saxman's doc): prevent next note from attacking ;zloc_DC4 cfPreventAttack: set 4,(ix+zTrack.PlaybackControl) ; Set bit 4 (10h) on playback control; do not attack next note dec hl ; Takes no argument, so just put it back ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): set note fill amount to xx ;zloc_DCA cfNoteFill: ld (ix+zTrack.NoteFillTimeout),a ; Note fill value (modifiable) ld (ix+zTrack.NoteFillMaster),a ; Note fill value (master copy, rewrites +0Fh when necessary) ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): add xx to channel key ;zloc_DD1 cfAddKey: cfChangeTransposition: add a,(ix+zTrack.Transpose) ; Add to current transpose value ld (ix+zTrack.Transpose),a ; Store updated transpose value ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): set music tempo to xx ;zloc_DD8 cfSetTempo: ld (zAbsVar.CurrentTempo),a ; Set tempo ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): Change Tempo Modifier to xx for ALL channels ;zloc_DDC cfSetTempoMod: push ix ; Save 'ix' ld ix,zTracksStart ; Start at beginning of track memory ld de,zTrack.len ; Track size ld b,MUSIC_TRACK_COUNT ; All 10 tracks - ld (ix+zTrack.TempoDivider),a ; Sets the timing divisor for ALL tracks; this can result in total half-speed, quarter-speed, etc. add ix,de djnz - pop ix ; Restore 'ix' ret ; --------------------------------------------------------------------------- ; This controls which TL registers are set for a particular ; algorithm; it actually makes more sense to look at a zVolTLMaskTbl entry as a bitfield. ; Bit 0-4 set which TL operators are actually effected for setting a volume; ; this table helps implement the following from the Sega Tech reference: ; "To make a note softer, only change the TL of the slots (the output operators). ; Changing the other operators will affect the flavor of the note." ; zloc_DF1: ensure1byteoffset 8 zVolTLMaskTbl: db 8, 8, 8, 8 db 0Ch,0Eh,0Eh,0Fh ; --------------------------------------------------------------------------- ; (via Saxman's doc): Change channel volume TO xx; xx is signed (Incorrect, see below) ; However, I've noticed this is incorrect; first of all, you'll notice ; it's still doing an addition, not a forced set. Furthermore, it's ; not actually altering the FM yet; basically, until the next voice ; switch, this volume change will not come into effect. Maybe a better ; description of it is "change volume by xx when voice changes", which ; makes sense given some voices are quieter/louder than others, and a ; volume change at voice may be necessary... or my guess anyway. ; Alternatively, just think of it as a volume setting optimized for PSG :P ;zloc_DF9 cfChangeVolume cfChangePSGVolume: add a,(ix+zTrack.Volume) ; Add to channel volume ld (ix+zTrack.Volume),a ; Store updated volume ret ; --------------------------------------------------------------------------- ; Unused command EDh ; This used to be Sonic 1's cfClearPush. The whole Push SFX feature ; was retained when the driver was ported to Z80, but eventually removed in Beta 5. ; This broken code is all that's left of it. ;zlocret_E00 cfUnused cfUnused1 cfClearPush: if (OptimiseDriver=0)&&(FixDriverBugs=0) ; Dangerous! It doesn't put back the byte read, meaning one gets skipped! ret endif ; --------------------------------------------------------------------------- ; Unused command EEh ; This used to be Sonic 1's cfStopSpecialFM4. But the Special SFX function hasn't been ported... ;zloc_E01 cfVoiceUNK cfUnused2 cfStopSpecialFM4: dec hl ; Put back byte; does nothing ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): set voice selection to xx ;zloc_E03 cfSetVoice: ld (ix+zTrack.VoiceIndex),a ; Set current voice ld c,a ; a -> c (saving for later, if we go to cfSetVoiceCont) bit 2,(ix+zTrack.PlaybackControl) ; If "SFX is overriding this track" bit set... ret nz ; .. return! push hl ; Save 'hl' call cfSetVoiceCont ; Set the new voice! pop hl ; Restore 'hl' ret ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_E12 cfSetVoiceCont: ld a,(zDoSFXFlag) ; Check SFX flag 0 = updating music, 80h means busy (don't supply me a sound, plz), FFh set means updating SFX (use custom voice table) or a ; test ld a,c ; c -> a (restored 'a') jr z,zSetVoiceMusic ; If not busy, jump to zSetVoiceMusic (set 'hl' to VoiceTblPtr) ld l,(ix+zTrack.VoicePtrLow) ; get low byte of custom voice table ld h,(ix+zTrack.VoicePtrHigh) ; get high byte of custom voice table jr zSetVoice ; Do not set 'hl' to VoiceTblPtr ; End of function cfSetVoiceCont ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_E21 zSetVoiceMusic: ; Set 'hl' to normal voice table pointer ld hl,(zAbsVar.VoiceTblPtr) ;zloc_E24 zSetVoice: ; This does the actual setting of the FM registers for the specific voice ; 'a' is the voice index to set ; 'hl' is set to the address of the voice table pointer (can be substituted, probably mainly for SFX) if OptimiseDriver ld e,a ld d,0 ld b,25 - add hl,de djnz - else push hl ; push 'hl' for the end of the following block... ; The following is a crazy block designed to 'multiply' our target voice value by 25... ; Where a single voice is 25 bytes long ld c,a ; a -> c ld b,0 ; b = 0 (so only low byte of 'bc' is set, basically voice to set) add a,a ; a *= 2 (indexing something...) ld l,a ; low byte of 'hl' set to 'a' ld h,b ; high byte = 0 add hl,hl ; hl *= 2 add hl,hl ; hl *= 2 (total hl * 4!!) ld e,l ld d,h ; de = hl add hl,hl ; hl *= 2 add hl,de ; hl += de add hl,bc ; hl += bc (waaah!) pop de ; old 'hl' value -> 'de' add hl,de ; hl += de (Adds address from the very beginning) ; End crazy multiply-by-25 block endif ; Sets up a value for future Total Level setting... ld a,(hl) ; Get feedback/algorithm -> a inc hl ; next byte of voice... ld (zloc_E65+1),a ; self-modifying code; basically enables 'a' restored to its current value later ld c,a ; a -> c (will be data to YM2612) ld a,(ix+zTrack.VoiceControl) ; Get "voice control" byte and 3 ; only keep bits 0-2 (bit 2 specifies which chip to write to) add a,0B0h ; add to get appropriate feedback/algorithm register rst zWriteFMIorII ; Write new value to appropriate part ; detune/coarse freq, all channels sub 80h ; Subtract 80h from 'a' (Detune/coarse frequency of operator 1 register) ld b,4 ; Do next 4 bytes (operator 1, 2, 3, and 4) - ld c,(hl) ; Get next detune/coarse freq inc hl ; next voice byte rst zWriteFMIorII ; Write this detune/coarse freq add a,4 ; Next detune/coarse freq register djnz - push af ; saving 'a' for much later... will be restored when time to "Total Level" ; other regs up to just before "Total Level", all channels add a,10h ; we're at 40h+, now at 50h+ (RS/AR of operator 1 register) ld b,10h ; Perform 16 writes (basically goes through RS/AR, AM/D1R, D2R, D1L) - ld c,(hl) ; Get next reg data value inc hl ; next voice byte rst zWriteFMIorII ; Write to FM add a,4 ; Next register djnz - ; Now going to set "stereo output control and LFO sensitivity" add a,24h ; Sets to reg B4h+ (stereo output control and LFO sensitivity) ld c,(ix+zTrack.AMSFMSPan) ; Panning / AMS / FMS settings from track rst zWriteFMIorII ; Write it! ld (ix+zTrack.TLPtrLow),l ; Save current position (TL bytes begin) ld (ix+zTrack.TLPtrHigh),h ; ... for updating volume correctly later later zloc_E65: ld a,0 ; "self-modified code" -- 'a' will actually be set to the feedback/algorithm byte and 7 ; Only keeping the "algorithm" part of it add a,zVolTLMaskTbl&0FFh ; Adds offset to zVolTLMaskTbl table (low byte only) ld e,a ; Puts this low byte into 'e' ld d,(zVolTLMaskTbl&0FF00h)>>8 ; Get high byte -> 'd' ld a,(de) ; Get this zVolTLMaskTbl value by algorithm ld (ix+zTrack.VolTLMask),a ; Store this zVolTLMaskTbl value into (ix+1Ah) ld e,a ; Store zVolTLMaskTbl value -> 'e' ld d,(ix+zTrack.Volume) ; Store channel volume -> 'd' pop af ; Restore 'a'; it's now back at appropriate 40h+ register for Total Level setting! ; Set "Total Levels" (general volume control) zSetFMTLs: ld b,4 ; Loop 4 times (for each Total Level register on this channel) - ld c,(hl) ; Get next TL byte -> c inc hl ; Next voice byte... rr e ; zVolTLMaskTbl value is rotated right; if the bit 0 of this value prior to the rotate was reset (0)... jr nc,++ ; ... then we make the jump here (just write the TL value directly, don't modify it) ; Otherwise, apply channel volume to TL here ; It's not appropriate to alter ALL TL values, only ; the ones which are "slots" (output operators) push af ; Save 'a' if FixDriverBugs res 7,c endif ld a,d ; Channel volume -> d add a,c ; Add it to the TL value if FixDriverBugs ; Prevent attenuation overflow (volume underflow) jp p,+ ld a,7Fh endif + ld c,a ; Modified value -> c pop af ; Restore 'a' + rst zWriteFMIorII ; Write TL value add a,4 ; Next TL reg... djnz - ret ; End of function zSetVoiceMusic ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_E8A zSetChanVol: bit 7,(ix+zTrack.VoiceControl) ; a PSG track ret nz ; If so, quit! bit 2,(ix+zTrack.PlaybackControl) ; If playback control byte "SFX is overriding this track" bit set... ret nz ; ... then quit! ld e,(ix+zTrack.VolTLMask) ; zVolTLMaskTbl value from last voice setting (marks which specific TL operators need updating) ld a,(ix+zTrack.VoiceControl) ; Load current voice control byte and 3 ; Keep only bits 0-2 add a,40h ; Add 40h -- appropriate TL register ld d,(ix+zTrack.Volume) ; Get channel volume bit 7,d ; If bit 7 (80h) is set... ret nz ; ... then quit! push hl ; Save 'hl' ld l,(ix+zTrack.TLPtrLow) ; low byte of where TL bytes begin (set during last voice setting) ld h,(ix+zTrack.TLPtrHigh) ; high byte of where TL bytes begin (set during last voice setting) call zSetFMTLs ; Set the appropriate Total Levels pop hl ; Restore 'hl' ret ; End of function zSetChanVol ; --------------------------------------------------------------------------- ; (via Saxman's doc): F0wwxxyyzz - modulation ; o ww - Wait for ww period of time before modulation starts ; o xx - Modulation Speed ; o yy - Modulation change per Mod. Step ; o zz - Number of steps in modulation ;zloc_EB0 cfModulation: set 3,(ix+zTrack.PlaybackControl) ; Set bit 3 (08h) of "playback control" byte (modulation on) dec hl ; Move 'hl' back one... ld (ix+zTrack.ModulationPtrLow),l ; Back up modulation setting address into (ix+11h), (ix+12h) ld (ix+zTrack.ModulationPtrHigh),h ;zloc_EBB zSetModulation: ; Sets up modulation for this track; expects 'hl' to point to modulation ; configuration info... ; Heh, using some undoc instructions here... ld a,ixl ; Get lower byte of current track address (ew :P) add a,zTrack.ModulationWait ; ... and add 19 bytes to it ld e,a ; put that into 'e' adc a,ixu ; If carry occurred, add that to upper part of address sub e ; subtract 'e' ld d,a ; Basically, 'd' is now the appropriate upper byte of the address, completing de = (ix + 19) ; Copying next three bytes if OptimiseDriver ld bc,3 ldir ; while (bc-- > 0) *de++ = *hl++; (wait, modulation speed, modulation change) else ldi ; *(de)++ = *(hl)++ (Wait for ww period of time before modulation starts) ldi ; *(de)++ = *(hl)++ (Modulation Speed) ldi ; *(de)++ = *(hl)++ (Modulation change per Mod. Step) endif ld a,(hl) ; Get Number of steps in modulation inc hl ; Next byte... srl a ; divide number of steps by 2 ld (ix+zTrack.ModulationSteps),a ; Store this step count into trackPtr+16h bit 4,(ix+zTrack.PlaybackControl) ; Is bit 4 "do not attack next note" (10h) set? ret nz ; If so, quit! xor a ; Clear 'a' ld (ix+zTrack.ModulationValLow),a ; Clear modulation value low byte ld (ix+zTrack.ModulationValHigh),a ; Clear modulation value high byte ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): Turn on modulation ;zloc_EDE cfEnableModulation: dec hl set 3,(ix+zTrack.PlaybackControl) ; Playback byte bit 3 (08h) -- modulation on ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): stop the track ;zloc_EE4 cfStopTrack: res 7,(ix+zTrack.PlaybackControl) ; Clear playback byte bit 7 (80h) -- currently playing (not anymore) res 4,(ix+zTrack.PlaybackControl) ; Clear playback byte bit 4 (10h) -- do not attack bit 7,(ix+zTrack.VoiceControl) ; Is voice control bit 7 (80h) a PSG track set? jr nz,zStopPSGTrack ; If so, skip this next part... ld a,(zAbsVar.DACUpdating) ; Is DAC updating? (FF if so) or a ; test it jp m,zDACStopTrack ; If DAC is updating, go here (we're in a DAC track) call zFMNoteOff ; Otherwise, stop this FM track jr + ;zcall_zsub_526 zStopPSGTrack: call zPSGNoteOff + ; General stop track continues here... ld a,(zDoSFXFlag) ; Check if we're an SFX track or a ; test it jp p,zStopMusicTrack ; If not, jump to zStopMusicTrack xor a ; a = 0 ld (zAbsVar.SFXPriorityVal),a ; Reset SFX priority ld a,(ix+zTrack.VoiceControl) ; Load "voice control" byte or a ; test it.. jp m,zStopPSGSFXTrack ; If this is PSG SFX track, jump to zStopPSGSFXTrack push ix ; save 'ix' ; This is an FM SFX track that's trying to stop sub 2 ; Take channel assignment - 2 (since SFX never use FM 1 or FM 2) add a,a ; a *= 2 (each table entry is 2 bytes wide) add a,zMusicTrackOffs&0FFh ; Get low byte value from zMusicTrackOffs ld (zloc_F1D+2),a ; store into the instruction after zloc_F1D (self-modifying code) zloc_F1D: ld ix,(zMusicTrackOffs) ; self-modified code from just above; 'ix' points to corresponding Music FM track bit 2,(ix+zTrack.PlaybackControl) ; If "SFX is overriding this track" is not set... jp z,+ ; Skip this part (i.e. if SFX was not overriding this track, then nothing to restore) call zBankSwitchToMusic ; Bank switch back to music track res 2,(ix+zTrack.PlaybackControl) ; Clear SFX is overriding this track from playback control set 1,(ix+zTrack.PlaybackControl) ; Set track as resting bit ld a,(ix+zTrack.VoiceIndex) ; Get voice this track was using call zSetVoiceMusic ; And set it! (takes care of volume too) bankswitch SoundIndex + pop ix ; restore 'ix' pop bc ; removing return address from stack; will not return to coord flag loop pop bc ; removing return address from stack; will not return to z*UpdateTrack function ret ; --------------------------------------------------------------------------- zStopPSGSFXTrack: push ix ; save 'ix' ; Keep in mind that we just entered with a PSG "voice control" byte ; which is one of the following values (PSG1-3/3N) -- 80h, A0h, C0h, E0h rra rra rra rra ; in effect, ">> 4" and 0Fh ; 'a' is now 08, 0A, 0C, or 0E add a,zMusicTrackOffs&0FFh ld (zloc_F5A+2),a ; store into the instruction after zloc_A5A (self-modifying code) zloc_F5A: ld ix,(zMusicTrackOffs) ; self-modified code from just above; 'ix' points to corresponding Music PSG track res 2,(ix+zTrack.PlaybackControl) ; Clear SFX is overriding this track from playback control set 1,(ix+zTrack.PlaybackControl) ; Set track as resting bit ld a,(ix+zTrack.VoiceControl) ; Get voice control byte cp 0E0h ; Is this a PSG 3 noise (not tone) track? jr nz,+ ; If it isn't, don't do next part (non-PSG Noise doesn't restore) ld a,(ix+zTrack.PSGNoise) ; Get PSG noise setting ld (zPSG),a ; Write it to PSG + pop ix ; restore 'ix' ;zloc_F75 zStopMusicTrack: pop bc ; removing return address from stack; will not return to coord flag loop ;zloc_F76 zDACStopTrack: pop bc ; removing return address from stack; will not return to z*UpdateTrack function (anything othat than DAC) or not to coord flag loop (if DAC) ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): Change current PSG noise to xx (For noise channel, E0-E7) ;zloc_F78 cfSetPSGNoise: ld (ix+zTrack.VoiceControl),0E0h ; This is a PSG noise track now! ld (ix+zTrack.PSGNoise),a ; Save PSG noise setting for restoration if SFX overrides it bit 2,(ix+zTrack.PlaybackControl) ; If SFX is currently overriding it, don't actually set it! ret nz ld (zPSG),a ; Otherwise, please do ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): Turn off modulation ;zloc_F88 cfDisableModulation: dec hl ; No parameters used, must back up a byte res 3,(ix+zTrack.PlaybackControl) ; Clear "modulation on" bit setting ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): Change current PSG tone to xx ;zloc_F8E cfSetPSGTone: ld (ix+zTrack.VoiceIndex),a ; Set current PSG tone ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): jump to position yyyy ;zloc_F92 cfJumpTo: ld h,(hl) ; Get hight byte of jump destination (since pointer advanced to it) ld l,a ; Put low byte (already retrieved) ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): $F7xxyyzzzz - repeat section of music ; * xx - loop index, for loops within loops without confusing the engine. ; o EXAMPLE: Some notes, then a section that is looped twice, then some more notes, and finally the whole thing is looped three times. ; The "inner" loop (the section that is looped twice) would have an xx of 01, looking something along the lines of F70102zzzz, whereas the "outside" loop (the whole thing loop) would have an xx of 00, looking something like F70003zzzz. ; * yy - number of times to repeat ; o NOTE: This includes the initial encounter of the F7 flag, not number of times to repeat AFTER hitting the flag. ; * zzzz - position to loop back to ;zloc_F95 cfRepeatAtPos: ; Loop index is in 'a' ld c,(hl) ; Get next byte (number of repeats) -> 'c' inc hl ; Next byte... push hl ; Save 'hl' add a,zTrack.LoopCounters ; Add to make loop index offset (starts at 20h in track memory) ld l,a ; Set hl = offset index ld h,0 ld e,ixl ; Set 'de' to beginning of track ld d,ixu add hl,de ; hl is now pointing to track memory offset for this loop ld a,(hl) ; Get loop count at this address or a ; Test it jr nz,+ ; If not zero, then skip next step (i.e. we're currently looping) ld (hl),c ; Otherwise, set it to the new number of repeats + dec (hl) ; One less loop pop hl ; Restore 'hl' (now at the position) jr z,+ ; If counted to zero, skip the rest of this (hence start loop count of 1 terminates the loop without ever looping) ld a,(hl) ; Get low byte of jump address inc hl ; Next byte ld h,(hl) ; Get high byte of jump address -> 'h' ld l,a ; Put low byte of jump address -> 'l' ; Note then that this loop command only works AFTER the section you mean to loop ret + ; If you get here, the loop terminated; just bypass the loop jump address inc hl inc hl ret ; --------------------------------------------------------------------------- ; (via Saxman's doc): jump to position yyyy (keep previous position in memory for returning) ;zloc_FB3 cfJumpToGosub: ld c,a ; a -> c ld a,(ix+zTrack.StackPointer) ; Get current "stack" offset (starts at 2Ah, i.e. beginning of next track) sub 2 ; Move back by two (we need to store a new return address) ld (ix+zTrack.StackPointer),a ; Set current stack offset ld b,(hl) ; Get high byte of jump position -> 'b' inc hl ; Next byte... ex de,hl ; hl <=> de add a,ixl ; Add low byte of current track pointer to stack offset (low byte of stack location) ld l,a ; Keep this in 'l' adc a,ixu ; Update high byte, if necessary sub l ; Fixup ld h,a ; a -> 'h' (Simply, we just did hl = ix + stack_offset) ld (hl),e ; Store current address low byte (just after jump) into stack inc hl ; Next byte ld (hl),d ; Store current address high byte (just after jump) into stack ld h,b ld l,c ; hl = bc (current location is where you wanted to jump to) ret ; --------------------------------------------------------------------------- ; Leftover from Sonic 1: was used in SYZ's music. ;zloc_FCC cfOpF9: ld a,88h ; D1L/RR of Operator 3 ld c,0Fh ; Loaded with fixed value (max RR, 1TL?) rst zWriteFMI ; Written to part I ld a,8Ch ; D1L/RR of Operator 4 ld c,0Fh ; Loaded with fixed value (max RR, 1TL?) rst zWriteFMI ; Written to part I dec hl ; Doesn't take an arg, so put back one byte ret ; --------------------------------------------------------------------------- ;zbyte_FD8h zSFXPriority: db 80h,70h,70h,70h,70h,70h,70h,70h,70h,70h,68h,70h,70h,70h,60h,70h db 70h,60h,70h,60h,70h,70h,70h,70h,70h,70h,70h,70h,70h,70h,70h,7Fh db 6Fh,70h,70h,70h,70h,70h,70h,70h,70h,70h,70h,70h,70h,6Fh,70h,70h db 70h,60h,60h,70h,70h,70h,70h,70h,70h,70h,60h,62h,60h,60h,60h,70h db 70h,70h,70h,70h,60h,60h,60h,6Fh,70h,70h,6Fh,6Fh,70h,71h,70h,70h db 6Fh ; zoff_1029: ;zPSG_Index zPSG_FlutterTbl: ; Basically, for any tone 0-11, dynamic volume adjustments are applied to produce a pseudo-decay, ; or sometimes a ramp up for "soft" sounds, or really any other volume effect you might want! ; Remember on PSG that the higher the value, the quieter it gets (it's attenuation, not volume); ; 0 is thus loudest, and increasing values decay, until level $F (silent) dw byte_1043, byte_105A, byte_1061, byte_1072 dw byte_108C, byte_107D, byte_10B6, byte_10D2 dw byte_10FA, byte_110B, byte_1149, byte_1165 dw byte_11E5 byte_1043: db 0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5 db 5,5,6,6,6,7,80h byte_105A: db 0,2,4,6,8,10h,80h byte_1061: db 0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,80h byte_1072: db 0,0,2,3,4,4,5,5,5,6,80h byte_107D: db 3,3,3,2,2,2,2,1,1,1,0,0,0,0,80h byte_108C: db 0,0,0,0,0,0,0,0,0,0,1,1 db 1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2 db 2,2,2,2,3,3,3,3,3,3,3,3,4,80h byte_10B6: db 0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2 db 3,3,3,4,4,4,5,5,5,6,7,80h byte_10D2: db 0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,2 db 3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,6 db 6,6,6,6,7,7,7,80h byte_10FA: db 0,1,2,3,4,5,6,7,8,9,0Ah,0Bh,0Ch,0Dh,0Eh,0Fh,80h byte_110B: db 0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1 db 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 db 1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2 db 2,2,3,3,3,3,3,3,3,3,3,3,4,80h byte_1149: db 4,4,4,3,3,3,2,2,2,1,1,1,1,1,1,1 db 2,2,2,2,2,3,3,3,3,3,4,80h byte_1165: db 4,4,3,3,2,2,1,1,1,1,1,1,1,1,1,1 db 1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2 db 2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3 db 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3 db 3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4 db 4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5 db 5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6 db 6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,80h byte_11E5: db 0Eh,0Dh,0Ch,0Bh,0Ah,9,8,7,6,5,4,3,2,1,0,80h ; END of zPSG_FlutterTbl --------------------------- ; zbyte_11F5h: zMasterPlaylist: ; Music IDs offset := MusicPoint2 ptrsize := 2 idstart := 80h ; note: +20h means uncompressed, here ; +40h is a flag that forces PAL mode off when set zMusIDPtr_2PResult: db id(MusPtr_2PResult) ; 92 zMusIDPtr_EHZ: db id(MusPtr_EHZ) ; 81 zMusIDPtr_MCZ_2P: db id(MusPtr_MCZ_2P) ; 85 zMusIDPtr_OOZ: db id(MusPtr_OOZ) ; 8F zMusIDPtr_MTZ: db id(MusPtr_MTZ) ; 82 zMusIDPtr_HTZ: db id(MusPtr_HTZ) ; 94 zMusIDPtr_ARZ: db id(MusPtr_ARZ) ; 86 zMusIDPtr_CNZ_2P: db id(MusPtr_CNZ_2P) ; 80 zMusIDPtr_CNZ: db id(MusPtr_CNZ) ; 83 zMusIDPtr_DEZ: db id(MusPtr_DEZ) ; 87 zMusIDPtr_MCZ: db id(MusPtr_MCZ) ; 84 zMusIDPtr_EHZ_2P: db id(MusPtr_EHZ_2P) ; 91 zMusIDPtr_SCZ: db id(MusPtr_SCZ) ; 8E zMusIDPtr_CPZ: db id(MusPtr_CPZ) ; 8C zMusIDPtr_WFZ: db id(MusPtr_WFZ) ; 90 zMusIDPtr_HPZ: db id(MusPtr_HPZ) ; 9B zMusIDPtr_Options: db id(MusPtr_Options) ; 89 zMusIDPtr_SpecStage: db id(MusPtr_SpecStage) ; 88 zMusIDPtr_Boss: db id(MusPtr_Boss) ; 8D zMusIDPtr_EndBoss: db id(MusPtr_EndBoss) ; 8B zMusIDPtr_Ending: db id(MusPtr_Ending) ; 8A zMusIDPtr_SuperSonic: db id(MusPtr_SuperSonic) ; 93 zMusIDPtr_Invincible: db id(MusPtr_Invincible) ; 99 zMusIDPtr_ExtraLife: db id(MusPtr_ExtraLife)+20h; B5 zMusIDPtr_Title: db id(MusPtr_Title) ; 96 zMusIDPtr_EndLevel: db id(MusPtr_EndLevel) ; 97 zMusIDPtr_GameOver: db id(MusPtr_GameOver)+20h ; B8 zMusIDPtr_Continue: db (MusPtr_Continue-MusicPoint1)/ptrsize ; 0 zMusIDPtr_Emerald: db id(MusPtr_Emerald)+20h ; BA zMusIDPtr_Credits: db id(MusPtr_Credits)+20h ; BD zMusIDPtr_Countdown: db id(MusPtr_Drowning)+40h ; DC zMusIDPtr__End: ; Tempo with speed shoe tempo for each song ;zbyte_1214 zSpedUpTempoTable: db 68h,0BEh,0FFh,0F0h db 0FFh,0DEh,0FFh,0DDh db 68h, 80h,0D6h, 7Bh db 7Bh,0FFh,0A8h,0FFh db 87h,0FFh,0FFh,0C9h db 97h,0FFh,0FFh,0CDh db 0CDh,0AAh,0F2h,0DBh db 0D5h,0F0h, 80h ; DAC sample pointers and lengths ensure1byteoffset 1Ch ;zDACPtr_Index: ;zbyte_1233: zDACPtrTbl: zDACPtr_Sample1: dw zmake68kPtr(SndDAC_Sample1) ;zbyte_1235 zDACLenTbl: dw SndDAC_Sample1_End-SndDAC_Sample1 zDACPtr_Sample2: dw zmake68kPtr(SndDAC_Sample2) dw SndDAC_Sample2_End-SndDAC_Sample2 zDACPtr_Sample3: dw zmake68kPtr(SndDAC_Sample3) dw SndDAC_Sample3_End-SndDAC_Sample3 zDACPtr_Sample4: dw zmake68kPtr(SndDAC_Sample4) dw SndDAC_Sample4_End-SndDAC_Sample4 zDACPtr_Sample5: dw zmake68kPtr(SndDAC_Sample5) dw SndDAC_Sample5_End-SndDAC_Sample5 zDACPtr_Sample6: dw zmake68kPtr(SndDAC_Sample6) dw SndDAC_Sample6_End-SndDAC_Sample6 zDACPtr_Sample7: dw zmake68kPtr(SndDAC_Sample7) dw SndDAC_Sample7_End-SndDAC_Sample7 ; something else for DAC sounds ; First byte selects one of the DAC samples. The number that ; follows it is a wait time between each nibble written to the DAC ; (thus higher = slower) ensure1byteoffset 22h ; zbyte_124F: zDACMasterPlaylist: ; DAC samples IDs offset := zDACPtrTbl ptrsize := 2+2 idstart := 81h db id(zDACPtr_Sample1),17h ; 81h db id(zDACPtr_Sample2),1 ; 82h db id(zDACPtr_Sample3),6 ; 83h db id(zDACPtr_Sample4),8 ; 84h db id(zDACPtr_Sample5),1Bh ; 85h db id(zDACPtr_Sample6),0Ah ; 86h db id(zDACPtr_Sample7),1Bh ; 87h db id(zDACPtr_Sample5),12h ; 88h db id(zDACPtr_Sample5),15h ; 89h db id(zDACPtr_Sample5),1Ch ; 8Ah db id(zDACPtr_Sample5),1Dh ; 8Bh db id(zDACPtr_Sample6),2 ; 8Ch db id(zDACPtr_Sample6),5 ; 8Dh db id(zDACPtr_Sample6),8 ; 8Eh db id(zDACPtr_Sample7),8 ; 8Fh db id(zDACPtr_Sample7),0Bh ; 90h db id(zDACPtr_Sample7),12h ; 91h ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ;zsub_1271 zSaxmanDec: if OptimiseDriver xor a ld b,a ld d,a ld e,a else exx ld bc,0 ld de,0 endif exx ld de,zMusicData ld c,(hl) inc hl ld b,(hl) ; bc = (hl) i.e. "size of song" inc hl ld (zGetNextByte+1),hl ; modify inst. @ zGetNextByte -- set to beginning of decompression stream if OptimiseDriver=0 inc bc endif ld (zDecEndOrGetByte+1),bc ; modify inst. @ zDecEndOrGetByte -- set to length of song, +1 ;zloc_1288 zSaxmanReadLoop: exx ; shadow reg set if OptimiseDriver srl b ; b >> 1 (just a mask that lets us know when we need to reload) jr c,+ ; if it's set, we still have bits left in 'c'; jump to '+' ; If you get here, we're out of bits in 'c'! call zDecEndOrGetByte ; get next byte -> 'a' ld c,a ; a -> 'c' ld b,7Fh ; b = 7Fh (7 new bits in 'c') + srl c ; test next bit of 'c' exx ; normal reg set jr nc,+ ; if bit not set, it's a compression bit; jump to '+' else srl c ; c >> 1 (active control byte) srl b ; b >> 1 (just a mask that lets us know when we need to reload) bit 0,b ; test next bit of 'b' jr nz,+ ; if it's set, we still have bits left in 'c'; jump to '+' ; If you get here, we're out of bits in 'c'! call zDecEndOrGetByte ; get next byte -> 'a' ld c,a ; a -> 'c' ld b,0FFh ; b = FFh (8 new bits in 'c') + bit 0,c ; test next bit of 'c' exx ; normal reg set jr z,+ ; if bit not set, it's a compression bit; jump to '+' endif ; If you get here, there's a non-compressed byte call zDecEndOrGetByte ; get next byte -> 'a' ld (de),a ; store it directly to the target memory address inc de ; de++ exx ; shadow reg set inc de ; Also increase shadow-side 'de'... relative pointer only, does not point to output Z80_RAM exx ; normal reg set jr zSaxmanReadLoop ; loop back around... + call zDecEndOrGetByte ; get next byte -> 'a' ld c,a ; a -> 'c' (low byte of target address) call zDecEndOrGetByte ; get next byte -> 'a' ld b,a ; a -> 'b' (high byte of target address + count) and 0Fh ; keep only lower four bits... add a,3 ; add 3 (minimum 3 bytes are to be read in this mode) push af ; save 'a'... ld a,b ; b -> 'a' (low byte of target address) rlca rlca rlca rlca and 0Fh ; basically (b >> 4) & 0xF (upper four bits now exclusively as lower four bits) ld b,a ; a -> 'b' (only upper four bits of value make up part of the address) ld a,c add a,12h ld c,a adc a,b sub c and 0Fh ld b,a ; bc += 12h pop af ; restore 'a' (byte count to read; no less than 3) exx ; shadow reg set push de ; keep current 'de' (relative pointer) value... ld l,a ; how many bytes we will read -> 'hl' ld h,0 add hl,de ; add current relative pointer... ex de,hl ; effectively, de += a exx ; normal reg set pop hl ; shadow 'de' -> 'hl' (relative pointer, prior to all bytes read, relative) or a ; Clear carry sbc hl,bc ; hl -= bc jr nc,+ ; if result positive, jump to '+' ex de,hl ; current output pointer -> 'hl' ld b,a ; how many bytes to load -> 'b' - ld (hl),0 ; fill in zeroes that many times inc hl djnz - ex de,hl ; output pointer updated jr zSaxmanReadLoop ; loop back around... + ld hl,zMusicData ; point at beginning of decompression point add hl,bc ; move ahead however many bytes ld c,a ld b,0 ldir jr zSaxmanReadLoop ; End of function zSaxmanDec ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| ; This is an ugly countdown to zero implemented in repeatedly modifying code!! ; But basically, it starts at the full length of the song +1 (so it can decrement) ; and waits until 'hl' decrements to zero ;zsub_12E8 zDecEndOrGetByte: ld hl,0 ; "self-modified code" -- starts at full length of song +1, waits until it gets to 1... if OptimiseDriver ld a,h or l jr z,+ ; If 'h' and 'l' both equal zero, we quit!! endif dec hl ; ... where this will be zero ld (zDecEndOrGetByte+1),hl ; "self-modifying code" -- update the count in case it's not zero if OptimiseDriver=0 ld a,h or l jr z,+ ; If 'h' and 'l' both equal zero, we quit!! endif ;zloc_12F3 zGetNextByte: ld hl,0 ; "self-modified code" -- get address of next compressed byte ld a,(hl) ; put it into -> 'a' inc hl ; next byte... ld (zGetNextByte+1),hl ; change inst @ zGetNextByte so it loads next compressed byte ret ; still going... + pop hl ; throws away return address to this function call so that next 'ret' exits decompressor (we're done!) ret ; Exit decompressor ; End of function zDecEndOrGetByte ; --------------------------------------------------------------------------- ; space for a few global variables zPALUpdTick: db 0 ; zbyte_12FE ; This counts from 0 to 5 to periodically "double update" for PAL systems (basically every 6 frames you need to update twice to keep up) zCurDAC: db 0 ; zbyte_12FF ; seems to indicate DAC sample playing status zCurSong: db 0 ; zbyte_1300 ; currently playing song index zDoSFXFlag: db 0 ; zbyte_1301; Flag to indicate we're updating SFX (and thus use custom voice table); set to FFh while doing SFX, 0 when not. zRingSpeaker: db 0 ; zbyte_1302 ; stereo alternation flag. 0 = next one plays on left, -1 = next one plays on right zGloopFlag: db 0 ; zbyte_1303 ; if -1, don't play the gloop sound next time zSpindashPlayingCounter: db 0 ; zbyte_1304 zSpindashExtraFrequencyIndex: db 0 ; zbyte_1305 zSpindashActiveFlag: db 0 ; zbyte_1306 ; -1 if spindash charge was the last sound that played zPaused: db 0 ; zbyte_1307 ; 0 = normal, -1 = pause all sound and music ; end of Z80 'ROM' if $>zMusicData fatal "Your Z80 code won't fit before the music.. It's \{$-zMusicData}h bytes past the start of music data \{zMusicData}h" endif
.global mydata mydata: .byte 0x78, 0x66, 0x69, 0x6f, 0x68, 0x66, 0x6f, 0x69, 0x68, 0x7a, 0x65, 0x6f, 0x69, 0x66, 0x68
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %rax push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x4665, %rsi lea addresses_A_ht+0x77e0, %rdi clflush (%rdi) nop nop add $30130, %rax mov $36, %rcx rep movsw nop nop nop nop nop cmp $31812, %rdx lea addresses_WC_ht+0xf220, %r14 dec %rbx movb (%r14), %al nop dec %rcx lea addresses_UC_ht+0x1ada0, %rax nop nop nop nop cmp %rsi, %rsi movb $0x61, (%rax) nop nop nop nop nop xor $40328, %rax lea addresses_WC_ht+0x11fe0, %rsi lea addresses_UC_ht+0x1db60, %rdi nop xor $24441, %r11 mov $76, %rcx rep movsw nop nop nop nop nop add %r11, %r11 lea addresses_normal_ht+0xf890, %rdi nop nop dec %rsi movups (%rdi), %xmm2 vpextrq $0, %xmm2, %rdx nop nop nop sub %rbx, %rbx lea addresses_A_ht+0x155e0, %r11 nop cmp $3117, %rdi movb (%r11), %dl nop nop nop and %rsi, %rsi lea addresses_normal_ht+0xcbe0, %rdx nop sub %rcx, %rcx movups (%rdx), %xmm6 vpextrq $0, %xmm6, %r14 nop nop nop nop and %r14, %r14 lea addresses_A_ht+0xbeb8, %rdi and %r14, %r14 mov $0x6162636465666768, %rbx movq %rbx, (%rdi) cmp $52617, %rdi lea addresses_A_ht+0x1cfe0, %rsi lea addresses_normal_ht+0x12180, %rdi nop lfence mov $33, %rcx rep movsw nop nop nop nop nop and $23546, %rdi lea addresses_WT_ht+0x12640, %rsi lea addresses_UC_ht+0x11fe0, %rdi add $59640, %rdx mov $60, %rcx rep movsq nop add %rax, %rax lea addresses_UC_ht+0xfa80, %rsi lea addresses_WT_ht+0x35c0, %rdi sub %rax, %rax mov $92, %rcx rep movsl nop nop nop nop nop mfence lea addresses_normal_ht+0x193e0, %r14 nop nop nop add $38991, %rbx movw $0x6162, (%r14) nop nop xor %r11, %r11 lea addresses_normal_ht+0x1e7e0, %rsi lea addresses_A_ht+0x17fa0, %rdi nop nop and %rax, %rax mov $85, %rcx rep movsq nop nop xor $42626, %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rax pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r15 push %rcx push %rdi push %rdx push %rsi // REPMOV lea addresses_normal+0x7a54, %rsi lea addresses_WT+0x10c20, %rdi inc %r15 mov $122, %rcx rep movsw nop nop nop nop nop xor %rsi, %rsi // REPMOV lea addresses_UC+0x198e0, %rsi lea addresses_normal+0x1afe0, %rdi nop nop mfence mov $104, %rcx rep movsl nop inc %r10 // Load lea addresses_UC+0xa180, %rsi xor %rdi, %rdi movb (%rsi), %r15b nop nop nop add %rdi, %rdi // Store lea addresses_UC+0xc2e0, %rcx nop nop nop xor $35242, %rsi mov $0x5152535455565758, %r12 movq %r12, %xmm5 movups %xmm5, (%rcx) nop inc %r10 // Store lea addresses_D+0xde0, %r15 nop nop inc %rdi mov $0x5152535455565758, %rdx movq %rdx, %xmm2 vmovups %ymm2, (%r15) nop nop nop dec %rdx // Store lea addresses_D+0x1a6a0, %r10 nop nop add $10270, %rsi movb $0x51, (%r10) nop nop nop cmp $38112, %r12 // Faulty Load lea addresses_RW+0x157e0, %r15 nop nop nop nop sub %r12, %r12 vmovups (%r15), %ymm0 vextracti128 $1, %ymm0, %xmm0 vpextrq $0, %xmm0, %rsi lea oracles, %rdx and $0xff, %rsi shlq $12, %rsi mov (%rdx,%rsi,1), %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %r15 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_RW', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_normal', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WT', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_UC', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_normal', 'congruent': 9, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_UC', 'same': False, 'size': 1, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_UC', 'same': False, 'size': 16, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D', 'same': False, 'size': 32, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D', 'same': False, 'size': 1, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_RW', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 1, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 1, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 16, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'same': False, 'size': 1, 'congruent': 8, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 16, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 8, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_UC_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 2, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': True}, 'dst': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM'} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
; ; ; ZX Maths Routines ; ; 12/12/02 - Stefano Bodrato ; ; $Id: ftoe.asm,v 1.2 2015/01/19 01:32:57 pauloscustodio Exp $ ; ; ; Just a dirty placeholder.. :oP PUBLIC ftoe EXTERN ftoa .ftoe jp ftoa
; A152064: a(n) = 2*n^3 - 3*n^2 + 5. ; 5,4,9,32,85,180,329,544,837,1220,1705,2304,3029,3892,4905,6080,7429,8964,10697,12640,14805,17204,19849,22752,25925,29380,33129,37184,41557,46260,51305,56704,62469,68612,75145,82080,89429,97204,105417,114080,123205,132804,142889,153472,164565,176180,188329,201024,214277,228100,242505,257504,273109,289332,306185,323680,341829,360644,380137,400320,421205,442804,465129,488192,512005,536580,561929,588064,614997,642740,671305,700704,730949,762052,794025,826880,860629,895284,930857,967360,1004805 mov $1,$0 mul $0,2 sub $0,3 mul $0,$1 mul $0,$1 add $0,5
/* * Copyright (c) 2011-2022, The DART development contributors * All rights reserved. * * The list of contributors can be found at: * https://github.com/dartsim/dart/blob/master/LICENSE * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <dart/dart.hpp> #include <dart/gui/osg/osg.hpp> #include <pybind11/eigen.h> #include <pybind11/pybind11.h> PYBIND11_DECLARE_HOLDER_TYPE(T, ::osg::ref_ptr<T>, true); namespace py = pybind11; namespace dart { namespace python { void ImGuiWidget(py::module& m) { ::pybind11::class_<dart::gui::osg::ImGuiWidget>(m, "ImGuiWidget") .def( "render", +[](dart::gui::osg::ImGuiWidget* self) { self->render(); }) .def( "setVisible", +[](dart::gui::osg::ImGuiWidget* self, bool visible) { self->setVisible(visible); }, ::pybind11::arg("visible")) .def( "toggleVisible", +[](dart::gui::osg::ImGuiWidget* self) { self->toggleVisible(); }) .def( "show", +[](dart::gui::osg::ImGuiWidget* self) { self->show(); }) .def( "hide", +[](dart::gui::osg::ImGuiWidget* self) { self->hide(); }) .def( "isVisible", +[](const dart::gui::osg::ImGuiWidget* self) -> bool { return self->isVisible(); }); } } // namespace python } // namespace dart
; THERE IS A STRING NAMED "ENG" ENDED WITH '$', SERCH "IS" IN THE STRING AND DISPLAY THE QUANTITY. DATA SEGMENT ENG DB 'THIS IS AN ENGLISH EXAMPLE.',0DH,0AH,'$' ; A STRING NAMED "ENG" LEN EQU $-ENG ; GET THE STRING'S LENGTH RESULT DB 'IS: $' ; SEARCH "IS" DATA ENDS CODE SEGMENT ASSUME CS:CODE,DS:DATA START: MOV AX,DATA MOV DS,AX LEA SI,ENG ; GET THE START ADDRESS OF ENG MOV CX,LEN-3 ; DECREASE 0DH 0AH $ WHICH ARE USED FOR DISPLAYING THEN SET A COUNTER MOV BX,0 ; STORE THE NUMBER OF "IS" SEARCH: CMP [SI],'I' ; COMPARE THE FIRST CHARACTER OF ENG WITH 'I' JNZ NOT_MATCH ; IF NOT COMPARED, JUMP TO NOT_MATCH CMP [SI+1],'S' ; OTHERWISE IT IS 'I' THEN COMPARE THE SECOND CHARACTER WITH 'S' JNZ NOT_MATCH MATCH: INC BX ; MATCHED, BX INCREASE 1 INC SI ; NOW SI IS STILL AT THE FIRST CHARACTER, SO SI INCREASE NOT_MATCH: INC SI ; GO TO THE NEXT CHARACTER CMP SI,CX JB SEARCH DISP: MOV AH,09H MOV DX,OFFSET ENG ; DISPLAY THE STRING INT 21H MOV AH,09H MOV DX,OFFSET RESULT ; DISPLAY THE RESULT INT 21H MOV AX,BX MOV BL,0AH ; BX IS DIVIDED BY 10 DIV BL MOV DL,AH ADD DL,'0' ; TURN BX TO CHARACTER NUMBER MOV AH,02H ; DISPLAY BX INT 21H CODE ENDS END START ; MY TEXTBOOK PROVIDES ANOTHER WAY TO ACHIEVE STRING MATCH: ; DATA SEGMENT ; ENG DB 'THIS IS AN PROGRAM EXAMPLE$' ; N1 EQU $-ENG ; STR DB 'IS' ; N2 EQU 4-STR ; DATA ENDS ; CODE SEGMENT ; ASSUME CS:CODE,DS:DATA,ES:DATA ; START: ; MOV AX,DATA ; MOV DS,AX ; MOV ES,AX ; XOR DX,DX ; MOV CL,N1 ; XOR CH,CH ; CMP CX,N2 ; JBE DISP ; MOV AL,STR ; LEA DI,ENG ; CLD ; SEARCH: ; REPNE SCASB ; JNE DISP ; MOV BL,STR+1 ; CMP ES:[DI],BL ; JE EXIST ; JCXZ DISP ; LOP: ; JMP SEARCH ; EXIST: ; INC DL ; CMP CX,1 ; JZ DISP ; JMP LOP ; DISP: ; OR DL,30H ; MOV AH,2 ; INT 21H ; MOV AH,4CH ; INT 21H ; CODE ENDS ; END START
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> findFrequentTreeSum(TreeNode* root) { maxCount = 0; treeSum(root); vector<int> result; for (auto t : table) { if (t.second == maxCount) { result.push_back(t.first); } } return result; } private: unordered_map<int, int> table; int maxCount; int treeSum(TreeNode* root) { if (root == nullptr) { return 0; } int left = treeSum(root->left); int right = treeSum(root->right); int sum = left + root->val + right; if (++table[sum] > maxCount) { maxCount = table[sum]; } return sum; } };
; A179546: a(n) = p^2*(p + 3)/2, where p = prime(n). ; 10,27,100,245,847,1352,2890,3971,6877,13456,16337,27380,36982,42527,55225,78652,107911,119072,157115,186517,202502,255881,296227,364366,470450,530452,562277,629695,665336,740602,1048385,1149787,1313830,1371791,1687276,1755677,1971920,2205227,2370565,2633752,2915731,3014012,3538657,3650402,3880900,3999701,4763747,5619377,5925835,6083156,6406102,6911641,7085882,8001127,8586370,9199477,9841096,10061417,10742060,11212462,11452727,12705652,14608595,15185197,15479102,16078240,18296687,19306730 seq $0,40 ; The prime numbers. add $1,$0 add $1,2 mul $1,$0 add $1,$0 mul $1,$0 div $1,2 mov $0,$1
map_header CinnabarMart, CINNABAR_MART, MART, 0 end_map_header
; char *strcpy_callee(char * restrict s1, const char * restrict s2) SECTION code_string PUBLIC _strcpy_callee EXTERN asm_strcpy _strcpy_callee: pop hl pop de ex (sp),hl jp asm_strcpy
LOAD A,10 STORE A,#(800) JMP 39 PUSH FP LOAD FP,SP LOAD A,#(FP+4) PUSH A LOAD A,1 PUSH A POP B POP A PLUS PUSH C POP A STORE A,#(FP+4) LOAD A,#(FP+4) PUSH A LOAD A,#(FP+3) PUSH A POP B POP A PLUS PUSH C LOAD A,#(FP+2) PUSH A POP B POP A PLUS PUSH C POP A PRINT A PRINTLN LOAD A,0 PUSH A POP C LOAD SP,FP POP FP RET 3 LOAD A,1 PUSH A LOAD A,1 PUSH A LOAD A,2 PUSH A POP B POP A PLUS PUSH C LOAD A,3 PUSH A LOAD A,4 PUSH A POP B POP A PLUS PUSH C LOAD A,5 PUSH A LOAD A,6 PUSH A POP B POP A PLUS PUSH C CALL 4 PUSH C POP B POP A PLUS PUSH C POP A PRINT A PRINTLN END
;************************************************************************** ; FILE: C:\PIC\freq_counter\counter1.asm * ; CONTENTS: Simple low-cost digital frequency meter using a PIC 16F628 * ; AUTHOR: Wolfgang Buescher, DL4YHF * ; (based on a work by James Hutchby, MadLab, 1996) * ; REVISIONS: (latest entry first) * ; 2019-06-28 - TheHWcave: added the capability to select counter mode * ; * ; 2019-05-02 - TheHWcave: added the capability to select RPM measurement * ; using 1 pulse, 2, 3 or 4 pulses per revolution, which * ; allows measuring 2 bladed, 3 or 4 bladed fans or propellers* ; and extended the range for RPM display. Frequency range is * ; now up to 200 Hz in period measurement. In RPM mode above * ; 255 Hz the normal frequency is used for conversion up to * ; around 92100 RPM in all 3 modes * ; 2019-04-18 - TheHWcave: major change: removed all variants except #2 and* ; the programming and frequency offset bits. Instead I added * ; period measurement for frequencies below 100 Hz which are * ; now shown with 2 decimal points. Pressing the button * ; toggles between RPM and frequency format (for frequencies * ; below 100 Hz / below 9999 RPM. The last setting is stored * ; in EEPROM and becomes the default at power-up * ; 2018-03-23 - TheHWcave: Changed to always use 5 digits in * ; DISPLAY_VARIANT_2 and _3 and also use 1Hz resolution * ; (Range 1) for Range 2 because with 5 digits it makes sense * ; to use the best resolution for as long as possible * ; 2006-05-31 - Added the 'power-save' option which temporarily puts the * ; PIC to sleep (with only the watchdog-oscillator running) * ; 2006-05-15 - New entry in the preconfigured frequency table for 4-MHz * ; IF filters (like "Miss Mosquita" [Moskita] by DK1HE) * ; 2005-08-24 - Cured a bug in the COMMON ANODE decimal point setting . * ; (the "^0xFF" for the AND-mask was missing in macro 'conv') * ; 2005-03-21 - Added a few conditionals to use the same sourcecode * ; to drive a COMMON ANODE display ( DISPLAY_VARIANT_3 ) * ; 2004-03-14 - Fixed a range-switching bug around 8 MHz . * ; - Support TWO different display variants now, * ; optimized for different board layouts, and different clock * ; frequencies (4 MHz for variant 1, 20 MHz for variant 2). * ; 2004-03-05 - Added the feature to add or subtract a frequency offset . * ; 2004-02-18 - Migration to a PIC16F628 with 4 MHz crystal (el Cheapo) * ; - Changed the LED patterns '6' and '9' because they looked * ; like 'b' and 'q' in the old counter version . * ; - Added the auto-ranging feature * ; - Stepped from 24-bit to 32-bit integer arithmetic, to be * ; able to count 50 MHz with 1-second gate time, * ; or (at least) adjust ANY result for the ANY prescaler * ; division ratio, which may give pretty large numbers . * ; - A PIC16F628 worked up to 63 MHz with this firmware . * ;************************************************************************** list P=16F628 #include <p16f628a.inc> ; processor specific definitions #define DEBUG 0 ; DEBUG=1 for simulation, DEBUG=0 for real hardware ;************************************************************************** ; * ; Summary * ; * ;************************************************************************** ; The software functions as a frequency meter with an input signal ; range of 1 Hz to ~ 50 MHz and with an accuracy of +/- 1Hz ; if the oscillator crystal is properly trimmed . ; Signal pulses are counted over a fixed time interval of 1/4 second to ; 1 second (gate time). High frequency pulses are counted over 1/4 s ; to make the meter more responsive with no loss of displayed accuracy. ; Pulses are counted using Timer 0 of the PIC, ; which is set to increment on rising edges on the TMR0 pin. The 8-bit ; hardware register is extended by software into a 32-bit pulse counter. ; If timer 0 rolls over (msb 1 -> 0) between successive polls then the ; high two bytes of the pulse counter are incremented. ; Timer 0 is unable to count more than one pulse per instruction cycle ; (per 4 clock cycles) so the prescaler is used at frequencies above ; 1MHz (4MHz clock / 4) and also to ensure that pulses are not lost ; between polls of timer 0 (which would happen if more than 128 pulses were ; received). Fortunately the prescaler is an asynchronous counter ; which works up to a few ten MHz (sometimes as far as 60 MHz) . ; Timing is based on a software loop of known execution period . The loop ; time is 20 us which gives integer counts to time 1 s and 1/4 s . ; During this timing loop, the multiplexed LED display is updated . ; ; To enable accurate low frequency measurenents, the timing loop also measures ; the period of the signal and accumulates these values over 1 second. This is ; later converted to frequency (or RPM) for frequencies < 100 Hz (166 for RPM) ; ; The frequency in binary is converted to decimal using a powers-of-ten ; lookup table. The binary powers of ten are repeatedly subtracted from ; the frequency to determine the individual decimal digits. The decimal ; digits are stored at the 8 bytes at 'digits'. Leading zeroes are then ; suppressed and the 4 (or 5) significant digits are converted to LED data ; for the 7-segment displays using a lookup table. ; The signal frequency is displayed on five 7-segment displays. ; The displays are multiplexed which means that only one display is enabled ; at any one time. The variable 'disp_index' contains the index of the currently ; enabled display. Each display is enabled in turn at a sufficient frequency ; that no flicker is discernable. A prescaler ('disp_timer') is used ; to set the multiplexing frequency to a few hundred Hz. ; The display shows the signal frequency in KHz or MHz, according to the ; following table: ; -------------------------------------- ; | | DISPLAY | ; | Frequency | Freq mode | RPMx1 mode| ; -------------------------------------- ; | < 1Hz | 0 | 0 ; | 1Hz | 001.00 | 00060 | Hz-dot is steady, no dot for RPM ; | 10Hz | 010.00 | 00600 | Hz-dot is steady, no dot for RPM ; | 99.99Hz | 099.99 | 06000 | Hz-dot is steady, no dot for RPM ; | 100Hz | 100.00 | 06000 | Khz-dot is flashing, no dot for RPM ; | 200Hz | 200.00 | 12000 | Khz-dot is flashing, no dot for RPM ; | 201Hz | 00.201 | 12060 | Khz-dot is flashing, no dot for RPM ; | 256Hz | 00.256 | 15360 | RPM display uses freq instead of period ; | 1535Hz | 01.535 | 92100 | max value for RPMx1 mode ; | 3071Hz | 03.071 | 92130 | max value for RPMx2 mode ; | 4607Hz | 04.607 | 92140 | max value for RPMx3 mode ; | 10.00KHz | 10.000 | 10.000 | ; | 100.0KHz | 100.00 | 100.00 | ; | 1.000MHz | 1.0000 | 1.0000 | Note1: MHz-dot is steady (not blinking) ; | 10.00MHz | 10.000 | 10.000 | Note2: for PRMx2..4 the display ; -------------------------------------- is one half/ third/ fourth of RPMx1 ; Note3: if max range for an RPM mode is ; exceeded, frequency is shown instead ; If there is no signal at all, a single zero is displayed in the 5th digit. ; Overflows are not displayed because they cannot be detected ! ;************************************************************************** ; * ; PIC config definitions * ; * ;************************************************************************** ; '__CONFIG' directive is used to embed configuration data within .asm file. ; The lables following the directive are located in the respective .inc file. ; See respective data sheet for additional information on configuration word. ; Since 2006-05-28, the watchdog must be ENABLE in the config word ; because of its wakeup-from-sleep function (see 'Sleep100ms') . ; EX(16F84:) __CONFIG _CP_OFF & _WDT_ON & _PWRTE_ON & _RC_OSC ; display variants 2+3 : clocked with 20 MHz (needs "HS" oscillator) __CONFIG _CP_OFF & _WDT_ON & _PWRTE_ON & _HS_OSC & _LVP_OFF & _BODEN_OFF & _MCLRE_OFF ; '__IDLOCS' directive may be used to set the 4 * 4(?!?) ID Location Bits . ; These shall be placed in the HEX file at addresses 0x2000...0x2003 . __IDLOCS H'1234' ; (definitions of "file" registers removed. They are defined in a header file!) ;************************************************************************** ; * ; Port assignments * ; * ;************************************************************************** PORT_A_IO equ b'0000' ; port A I/O mode (all output) PORT_B_IO equ b'00000000' ; port B I/O mode (all output) LEDS_PORT equ PORTB ; 7-segment LEDs port ENABLE_PORT equ PORTA ; display enable port ; Bitmasks to control the digit outputs have been moved to enable_table . ; YHF: Note that 'display #0' is the MOST SIGNIFICANT digit ! #define IOP_PROG_MODE PORTA,5 ; digital input signal, LOW enters programming mode ;************************************************************************** ; * ; Constants and timings * ; * ;************************************************************************** ; display variants 2+3 : clocked with 20 MHz (higher resolution) CLOCK equ .20000000 ; microseconds per timing loop ; clocked with 20 MHz ; 20 microseconds is possible with 20-MHz-Crystal, ; Make sure all gate times can be divided by this interval without remainder : ; 1 second / 20 us = 50000 (ok) ; 1/4 second / 20 us = 12500 (ok) ; 1/8 second / 50 us = 6250 (ok) TIME equ .20 ; Clock cycles per timing loop. See subroutine count_pulses . ; Usually CYCLES=200 (for 4 MHz crystal, 50 usec - loop) ; or 400 (for 20 MHz crystal, 20 usec - loop) CYCLES equ TIME*CLOCK/.1000000 GATE_TIME_LOOPS equ CLOCK/CYCLES ; number of gate-time loops for ONE SECOND gate time LAMPTEST_LOOPS equ CLOCK/(.2*CYCLES) ; number of loops for a 0.5 SECOND lamp test after power-on PROGMODE_LOOPS equ CLOCK/(.10*CYCLES) ; number of delay loops for display in PROGRAMMING MODE (0.1 sec) ; Configuration of power-saving mode : #if( DEBUG ) PSAVE_DELAY_TIME equ .10 ; number of 0.25-sec-intervals before turning off (shorter for debugging) #else PSAVE_DELAY_TIME equ .60 ; number of 0.25-sec-intervals before turning off (some dozen seconds) #endif PSAVE_FLASHUP_TIME equ .14 ; number of 0.7(!)-second-intervals between two flashes in power-saving mode PSAVE_MAX_DIFF equ .10 ; maximum frequency difference (range-dependent, see below) ; Unit: N times "frequency-resolution", see frequency-range table . ; Example: PSAVE_MAX_DIFF=10 means 10*4Hz in Range 1 (1..3.4 MHz) . ; Menu Indices ... must match the jump table PMDisplay + PMExecute ! MI_QUIT equ 0 ; exit from menu MI_PSAVE equ 1 ; turn "power save"-option on and off MI_ADD equ 2 ; save frequency offset to ADD it from now on MI_SUB equ 3 ; save frequency offset to SUBTRACT it from now on MI_ZERO equ 4 ; set the frequency offset to ZERO and leave menu MI_STD_IF equ 5 ; jump into the STANDARD INTERMEDIATE FREQUENCY table.. MI_INDEX_MAX equ 5 ; normal menu indices up to MI_INDEX_MAX . MI_IF_1 equ 6 ; show the 1st standard IF MI_IF_2 equ 7 ; show the 2nd standard IF MI_IF_3 equ 8 ; show the 3rd standard IF MI_IF_4 equ 9 ; show the 4th standard IF MI_IF_5 equ 0x0A ; show the 4th standard IF MI_IF_QT equ 0x0B ; exit standard IF menu without changing anything MI_IF_SUBMENU_MAX equ 0x0A ;************************************************************************** ; * ; File register usage * ; * ;************************************************************************** ; RAM memory (general purpose registers, unfortunately not the same for PIC16F84 & PIC16F628) ; in PIC16F628: RAM from 0x20..0x7F (96 bytes, 0x20.. only accessable in Bank0) ; 0xA0..0xEF (another 80 bytes in Bank1) ; 0x120..0x14F (another 48 bytes in Bank2) ; 0x0F0..0x0FF, 0x170..0x17F , 0x1F0..0x1FF are mapped to 0x70..0x7F (same in all banks) ; So use 0x70..0x7F for context saving in the PIC16F628 and forget 0x0F0.. 0xNNN ! ; ; Note on the 32-bit integer arithmetics as used in this code: ; - They begin with MOST SIGNIFICANT BYTE in memory, but... ; - Every byte location has its own label here, which makes debugging ; with Microchip's simulator much easier (point the mouse on the name ; of a variable to see what I mean !) ; ; tens_index equ 0x27 ; index into the powers-of-ten table divi equ 0x28 ; power of ten (32 bits) divi_hi equ 0x28 ; same as 'divi' : HIGH byte divi_mh equ 0x29 ; MEDIUM HIGH byte divi_ml equ 0x2A ; MEDIUM LOW byte divi_lo equ 0x2B ; LOW byte timer0_old equ 0x2C ; previous reading from timer0 register gatecnt_hi equ 0x2D ; 16-bit counter (msb first) gatecnt_lo equ 0x2E ; 16-bit counter (lsb last) bTemp equ 0x2F ; temporary 8-bit register, ; may be overwritten in ALL subroutines freq equ 0x30 ; frequency in binary (32 bits).... freq_hi equ 0x30 ; same location, begins with HIGH byte freq_mh equ 0x31 ; ... medium high byte freq_ml equ 0x32 ; ... medium low byte freq_lo equ 0x33 ; ... low byte freq2 equ 0x34 ; frequency too, freq2_hi equ 0x34 ; same location, begins with HIGH byte freq2_mh equ 0x35 ; ... medium high byte freq2_ml equ 0x36 ; ... medium low byte freq2_lo equ 0x37 ; ... low byte pstart_hi equ 0x38 ; holds the gatecnt at start of period measurement (high byte) pstart_lo equ 0x39 ; ... low byte t0dark equ 0x3A ; counter mode only: value tmr0 increased during dark time (outside count_pulses) t0last equ 0x3B ; counter mode only: value of tmr0 at the end of count_pulses menu_index equ 0x3C ; menu item for programming mode menu_timer equ 0x3D ; used to detect how long a key was pressed digits equ 0x40 ; frequency as decimal digits (8 bytes)... digit_0 equ 0x40 ; same location as MOST SIGNIFICANT digit, 10-MHz digit_1 equ 0x41 ; usually the 1-MHz-digit digit_2 equ 0x42 ; usually the 100-kHz-digit digit_3 equ 0x43 ; usually the 10-kHz-digit digit_4 equ 0x44 ; usually the 1-kHz-digit digit_5 equ 0x45 ; usually the 100-Hz-digit digit_6 equ 0x46 ; usually the 10-Hz-digit digit_7 equ 0x47 ; usually the 1-Hz-digit digit_8 equ 0x48 ; must contain a blank character (or trailing zero) display0 equ 0x49 ; display #0 data display1 equ 0x4A ; display #1 data display2 equ 0x4B ; display #2 data display3 equ 0x4C ; display #3 data display4 equ 0x4D ; display #4 data disp_index equ 0x4E ; index of the enabled display (0 to 4 for 5-digit display) disp_timer equ 0x4F ; display multiplex timer (5 bits) adjust_shifts equ 0x50 ; count of 'left shifts' to compensate prescaler+gate time blinker equ 0x51 ; prescaler for the flashing 1-kHz-dot psave_timer equ 0x52 ; timer for power-save mode (incremented every 0.25 seconds) psave_freq_lo equ 0x53 ; low-byte of frequency to detect changes for power-save mode psave_flags equ 0x54 ; power-saving flags with the following bits: #define PSFLAG_ACTIVE psave_flags,0 ; clear:normal mode, set:power-saving in action (display blanked) options equ 0x55 ; display options with the following flag-bits: #define OPT_PWRSAVE options,0 ; clear:normal mode, set:power-saving mode enabled period_waste equ 0x56 ; stores the number of cycle*4 to waste to make up the correct total ; ... number of instructions in the count_pulses loop pcnt equ 0x57 ; number of periods measured period_hi equ 0x58 ; accumulated period in 20us increments (high byte) period_lo equ 0x59 ; ... low byte pdiv_mh equ 0x5A ; used to store the final division result (bits 16..23) pdiv_ml equ 0x5B ; ... bits 8..15 pdiv_lo equ 0x5C ; ... bits 0..7 pmodeflag equ 0x5D ; 7 6 5 4 3 2 1 0 ; 0 - - - - 0 x x = period measuring off (normal freq disp) ; 1 - - - - 0 0 0 = PMODE_ON + Frequency ; 1 - - - - 0 0 1 = PMODE_ON + RPM x 1 ; 1 - - - - 0 1 0 = PMODE_ON + RPM x 2 ; 1 - - - - 0 1 1 = PMODE_ON + RPM x 3 ; 1 - - - - 1 0 0 = PMODE_ON + RPM x 4 ; 0 - - - - 1 0 1 = period measuring off (counter) #define PMODE_ON pmodeflag,7 ; 0 = off, 1 = on PMODE_RPM_1 equ .1 ; 1 pulse per revolution PMODE_RPM_2 equ .2 ; 2 pulses per revolution PMODE_RPM_3 equ .3 ; 3 pulses per revolution PMODE_RPM_4 equ .4 ; 4 pulses per revolution ONESECOND equ .50000 ; 1 second in 20 us units PERIOD2FREQ equ ONESECOND * .100 ; convert periods into HZ with 2 decimal points PERIOD2RPM_1 equ ONESECOND * .60 ; convert periods to RPM x 1 with no decimal point PERIOD2RPM_2 equ ONESECOND * .30 ; convert periods to RPM x 2 with no decimal point PERIOD2RPM_3 equ ONESECOND * .20 ; convert periods to RPM x 3 with no decimal point PERIOD2RPM_4 equ ONESECOND * .15 ; convert periods to RPM x 4 with no decimal point ; FREQ2RPM_1 equ .60 ; multiplier for direct freq to RPM x 1 FREQ2RPM_2 equ .30 ; multiplier for direct freq to RPM x 2 FREQ2RPM_3 equ .20 ; multiplier for direct freq to RPM x 3 FREQ2RPM_4 equ .15 ; multiplier for direct freq to RPM x 4 ;************************************************************************** ; * ; Macros (1) * ; * ;************************************************************************** eep_dw macro value ; a DOUBLEWORD split into 4 bytes in the PIC's DATA EEPROM de (value>>.24), (value>>.16)&0xFF, (value>>8)&0xFF, value&0xFF endm ;************************************************************************** ; * ; EEPROM memory definitions * ; * ;************************************************************************** ; for PIC16F84: 0x00..0x3F were valid EEPROM locations (64 byte) ; for PIC16F628: 0x00..0x7F are valid EEPROM locations (128 byte) #define EEPROM_ADR_FREQ_OFFSET 0x00 ; EEPROM location for frequency offset #define EEPROM_ADR_STD_IF_TABLE 0x04 ; EEPROM location for standard IF table (4*4 byte) #define EEPROM_ADR_OPTIONS 0x20 ; EEPROM location for "options" (flags) ; Initial contents of DATA EEPROM: org (0x2100+EEPROM_ADR_FREQ_OFFSET) eep_dw .0 ; [00..03] initial frequency offset = ZERO org (0x2100+EEPROM_ADR_STD_IF_TABLE) ; standard IF table ... eep_dw .455000 ; [04..07] frequently used in old AM radios eep_dw .3999000 ; [08..0B] used in "Miss Mosquita" (DK1HE / DL QRP AG) eep_dw .4194304 ; [0C..0F] used in other homebrew amateur radio receivers eep_dw .4433619 ; [10..13] sometimes used in homebrew amateur radio receivers eep_dw .10700000 ; [14..17] frequently used in old FM radios ; [18..1F] reserved for other "preprogrammed" values org (0x2100+EEPROM_ADR_OPTIONS) de .0 ; [20] "options" (flags), cleared by default ;************************************************************************** ; * ; More Macros * ; * ;************************************************************************** ;-------------------------------------------------------------------------- ; macros to implement lookup tables - these macros hide the PIC syntax ; used and make the source code more readable ; (YHF: CAUTION - BUT THESE MACROS HIDE SOME VERY NASTY PITFALLS . ; TABLE MUST NOT CROSS PAGE BORDER DUE TO 'ADDWF PCL, f' ! ) ;-------------------------------------------------------------------------- cquad macro value retlw value>>.24 ; high byte retlw (value>>.16)&0xFF ; middle-high byte retlw (value>>8)&0xFF ; middle-low byte retlw value&0xFF ; low byte endm table macro label ; define lookup table label addwf PCL,f ; caution: this is 'PCL' only, cannot add to the full 'PC' in a PIC ! endm ;-------------------------------------------------------------------------- ; add with carry - adds the w register and the carry flag to the file ; register reg, returns the result in <reg> with the carry flag set if overflow ;-------------------------------------------------------------------------- addcwf macro reg local add1,add2 bnc add1 ; branch if no carry set addwf reg , f ; add byte incf reg , f ; add carry skpnz setc goto add2 add1 addwf reg,f ; add byte add2 endm ;-------------------------------------------------------------------------- ; subtract with "no-carry" - subtracts the w register and the no-carry flag ; from the file register reg, returns the result in reg with the no carry flag ; set if underflow ;-------------------------------------------------------------------------- subncwf macro reg local sub1,sub2 bc sub1 ; branch if carry set subwf reg, f ; subtract byte skpnz ; subtract no carry clrc decf reg , f goto sub2 sub1 subwf reg , f ; subtract byte sub2 endm ;-------------------------------------------------------------------------- ; MACRO to perform 32-bit addition - adds the four bytes at op2 to the ; three bytes at op1 (most significant bytes first), returns the result in ; op1 with op2 unchanged and the carry flag set if overflow ;-------------------------------------------------------------------------- add32 macro op1,op2 ; op1 := op1 + op2 movfw op2+3 ; add low byte (bits 7...0) addwf op1+3,f movfw op2+2 ; add middle-low byte (bits 15..8) addcwf op1+2 movfw op2+1 ; add middle-high byte (bits 23...16) addcwf op1+1 movfw op2+0 ; add high byte (bits 31...24) addcwf op1+0 endm ;-------------------------------------------------------------------------- ; MACRO to perform 32-bit subtraction - subtracts the four bytes at op2 ; from the four bytes at op1 (most significant bytes first), returns the ; result in op1 with op2 unchanged and the no carry flag set if underflow ;-------------------------------------------------------------------------- sub32 macro op1,op2 ; op1 := op1 - op2 movfw op2+3 ; subtract low byte subwf op1+3 , f movfw op2+2 ; subtract middle low byte subncwf op1+2 movfw op2+1 ; subtract middle high byte subncwf op1+1 movfw op2+0 ; subtract high byte subncwf op1+0 endm ;-------------------------------------------------------------------------- ; MACRO to negate a 32-bit value ( op := 0 - op ) . ;-------------------------------------------------------------------------- neg32 macro op ; op1 := 0 - op2 local neg_done comf op, f ; invert all 8 bits in high byte comf op+1, f ; invert all 8 bits in middle high byte comf op+2, f ; invert all 8 bits in middle low byte comf op+3, f ; invert all 8 bits in low byte ; Note at this point 0x000000 would have turned into 0xFFFFFFF . ; Must add ONE to complete the TWO's COMPLIMENT calculation ( -0 = 0 ). ; Note that "incf" affects only the Z flag but not the C flag . incfsz op+3, f ; increment low byte (bits 7...0) goto neg_done ; if incremented result NOT zero, we're through ! incfsz op+2, f ; increment middle low byte (bits 15...8) goto neg_done ; if incremented result NOT zero, ... incfsz op+1, f ; increment middle high byte (bits 23...16) goto neg_done ; if ... incfsz op+0, f ; increment high byte (bits 31...24) goto neg_done ; neg_done endm ;-------------------------------------------------------------------------- ; MACRO to perform 32-bit subtraction - subtracts the four bytes at op2 ; from the four bytes at op1 (most significant bytes first), returns the ; result in op1 with op2 unchanged and the no carry flag set if underflow ;-------------------------------------------------------------------------- subx32 macro src,dst ;dst := dst - src bsf STATUS, C movf src+3,w btfss STATUS, C incfsz src+3,w subwf dst+3,f movf src+2,w btfss STATUS, C incfsz src+2,w subwf dst+2,f movf src+1,w btfss STATUS, C incfsz src+1,w subwf dst+1,f movf src+0,w btfss STATUS, C incfsz src+0,w subwf dst+0,f endm addx32 macro src,dst ;dst := dst + src bcf STATUS, C movf src+3,w btfsc STATUS, C incfsz src+3,w addwf dst+3,f movf src+2,w btfsc STATUS, C incfsz src+2,w addwf dst+2,f movf src+1,w btfsc STATUS, C incfsz src+1,w addwf dst+1,f movf src+0,w btfsc STATUS, C incfsz src+0,w addwf dst+0,f endm ;********************************************************************** ORG 0x000 ; processor reset vector goto MainInit ; go to beginning of program ; (begin of ROM is too precious to waste for ordinary code, see below...) ;************************************************************************** ; * ; Lookup tables * ; Must be at the start of the code memory to avoid crossing pages !! * ; * ;************************************************************************** ;-------------------------------------------------------------------------- ; 7-segment LED data table ;-------------------------------------------------------------------------- ; Index 0..9 used for decimal numbers, all other indices defined below : CHAR_A equ .10 ; Letters A..F = HEX digits, index 10..15 CHAR_b equ .11 ; CHAR_c equ .12 ; CHAR_d equ .13 ; CHAR_E equ .14 ; CHAR_F equ .15 ; CHAR_G equ .16 ; Other letters used in "programming" mode CHAR_H equ .17 ; CHAR_i equ .18 ; BLANK equ .19 ; blank display TEST equ .20 ; power-on display test CHAR_P equ .21 ; A few other letters for programming mode... CHAR_r equ .22 ; CHAR_o equ .23 ; "Prog" CHAR_Q equ .24 ; "Quit" CHAR_u equ .25 ; CHAR_t equ .26 ; CHAR_S equ .27 ; "Sub" CHAR_Z equ .28 ; "ZEro" CHAR_I equ .29 ; large "I" (left aligned!) for "IF" CHAR_J equ .30 ; CHAR_k equ .31 ; CHAR_L equ .32 ; CHAR_N equ .33 ; CHAR_V equ .34 ; CHAR_EQ equ .35 ; "=" DPPOINT_BIT equ 1 ; decimal point bit (same for all digits) #define _A 0x40 ; bitmask for segment A , etc .. #define _B 0x80 #define _C 0x04 #define _D 0x01 #define _E 0x08 #define _F 0x10 #define _G 0x20 #define _DP 0x02 BLANK_PATTERN equ b'00000000' ; blank display pattern (7-segment code) ;----------------------------------------------------------------------------- ; Table to convert a decimal digit or a special character into 7-segment-code ; Note: In DL4YHF's PIC counter, all digits have the same segment connections, ; so we do not need individual conversion tables for all segments. ; ; AAAA ; F B ; F B ; GGGG ; E C ; E C ; DDDD DP ; ;----------------------------------------------------------------------------- Digit2SevenSeg: addwf PCL,f ; caution: this is 'PCL' only, not 'PC'. Beware of page borders. ; A = 0, B = 1, C = 5, D = 3, E = 2, F = 6, G = 7, DP = 4 #define SSEG_XORMASK 0x00 ; for COMMON CATHODE: No bitwise EXOR to the pattern retlw (_A+_B+_C+_D+_E+_F )^SSEG_XORMASK ; ABCDEF. = '0' ( # 0 ) retlw ( _B+_C )^SSEG_XORMASK ; .BC.... = '1' ( # 1 ) retlw (_A+_B +_D+_E +_G)^SSEG_XORMASK ; AB.DE.G = '2' ( # 2 ) retlw (_A+_B+_C+_D +_G)^SSEG_XORMASK ; ABCD..G = '3' ( # 3 ) retlw ( _B+_C +_F+_G)^SSEG_XORMASK ; .BC..FG = '4' ( # 4 ) retlw (_A +_C+_D +_F+_G)^SSEG_XORMASK ; A.CD.FG = '5' ( # 5 ) retlw (_A +_C+_D+_E+_F+_G)^SSEG_XORMASK ; A.CDEFG = '6' ( # 6 ) retlw (_A+_B+_C )^SSEG_XORMASK ; ABC.... = '7' ( # 7 ) retlw (_A+_B+_C+_D+_E+_F+_G)^SSEG_XORMASK ; ABCDEFG = '8' ( # 8 ) retlw (_A+_B+_C+_D +_F+_G)^SSEG_XORMASK ; ABCD.FG = '9' ( # 9 ) retlw (_A+_B+_C +_E+_F+_G)^SSEG_XORMASK ; ABC.EFG = 'A' ( # 10 ) retlw ( _C+_D+_E+_F+_G)^SSEG_XORMASK ; ..CDEFG = 'b' ( # 11 ) retlw ( _D+_E +_G)^SSEG_XORMASK ; ...DE.G = 'c' ( # 12 ) retlw ( _B+_C+_D+_E +_G)^SSEG_XORMASK ; .BCDE.G = 'd' ( # 13 ) retlw (_A +_D+_E+_F+_G)^SSEG_XORMASK ; A..DEFG = 'E' ( # 14 ) retlw (_A +_E+_F+_G)^SSEG_XORMASK ; A...EFG = 'F' ( # 15 ) retlw (_A +_C+_D+_E+_F )^SSEG_XORMASK ; A.CDEF. = 'G' ( # 16 ) retlw ( _B+_C +_E+_F+_G)^SSEG_XORMASK ; .BC.EFG = 'H' ( # 17 ) retlw ( _E )^SSEG_XORMASK ; ....E.. = 'i' ( # 18 ) retlw (BLANK_PATTERN )^SSEG_XORMASK ; ....... = ' ' ( # 19 ) retlw (b'11111111' )^SSEG_XORMASK ; all segments on ( # 20 ) ; A few more letters for programming mode : retlw (_A+_B +_E+_F+_G)^SSEG_XORMASK ; AB..EFG = 'P' ( # 21 ) retlw ( _E +_G)^SSEG_XORMASK ; ....E.G = 'r' ( # 22 ) retlw ( _C+_D+_E +_G)^SSEG_XORMASK ; ..CDE.G = 'o' ( # 23 ) retlw (_A+_B+_C +_F+_G)^SSEG_XORMASK ; ABC..FG = 'Q' ( # 24 ) retlw ( _C+_D+_E )^SSEG_XORMASK ; ..CDE.. = 'u' ( # 25 ) retlw ( _D+_E+_F+_G)^SSEG_XORMASK ; ...DEFG = 't' ( # 26 ) retlw (_A +_C+_D +_F+_G)^SSEG_XORMASK ; A.CD.FG = 'S' ( # 27 ) retlw (_A+_B +_D+_E +_G)^SSEG_XORMASK ; AB.DE.G = 'Z' ( # 28 ) retlw ( _E+_F )^SSEG_XORMASK ; ....EF. = 'I' ( # 29 ) retlw ( _B+_C+_D )^SSEG_XORMASK ; .BCD.. = 'J' ( # 30 ) retlw ( _D+_E+_F+_G)^SSEG_XORMASK ; ...DEFG = 'k' ( # 31 ) retlw ( _D+_E+_F )^SSEG_XORMASK ; ...DEF. = 'L' ( # 32 ) retlw (_A+_B+_C +_E+_F )^SSEG_XORMASK ; ABC.EF. = 'N' ( # 33 ) retlw ( _C+_D+_E+_F )^SSEG_XORMASK ; ..CDEF. = 'V' ( # 34 ) retlw ( _D +_G)^SSEG_XORMASK ; ...D..G = '=' ( # 35 ) ;-------------------------------------------------------------------------- ; Table to control which 7-segment display is enabled. Displays are usually ; COMMON CATHODE (variants 1+2) so pulled low to enable. ; For DISP_VARIANT=3 (COMMON ANODE), the digit-driving pattern is inverted. ; Input: W = 0 means the MOST SIGNIFICANT DIGIT (the leftmost one), etc. ; Result: VALUE to be written to ENABLE_PORT to activate the digit ;-------------------------------------------------------------------------- Digit2MuxValue: ; addwf PCL,f ; caution: this is 'PCL' only, not 'PC' ; Note: If the program counter is affected, a command requires to instruction cycles (=8 osc cycles) ; muliplexer values (5 digits, COMMON CATHODE) : retlw b'11110111' ; most significant digit is on PA3 (!) retlw b'11111011' ; next less significant dig. on PA2 (!!) retlw b'11111110' ; next less significant dig. on PA0 (!!) retlw b'11111101' ; 4th (sometimes the last) digit PA1 (!) retlw b'11111111' ; 5th (OPTIONAL) least significant digit = NOT (PA3+PA2+PA1+PA0) ;-------------------------------------------------------------------------- ; Powers-of-ten table (32 bits, most significant byte first) ; Based on an idea by James Hutchby (MadLab, 1996) . ; Modified for 32-bit arithmetic by Wolfgang Buescher (2004). ;-------------------------------------------------------------------------- TensTable addwf PCL,f cquad .10000000 ; 10 million is sufficient for the counter itself cquad .1000000 cquad .100000 cquad .10000 cquad .1000 cquad .100 cquad .10 cquad .1 ;************************************************************************** ; * ; Procedures * ; * ;************************************************************************** ;-------------------------------------------------------------------------- ; Configure the prescaler for TIMER 0 in the PIC's OPTION register . ;-------------------------------------------------------------------------- ; Description of the OPTION register, from the PIC16F628 data sheet: ; bit 7: RBPU: PORTB Pull-up Enable bit ; 1 = PORTB pull-ups are disabled ; 0 = PORTB pull-ups are enabled by individual port latch values ; bit 6: INTEDG: Interrupt Edge Select bit ; 1 = Interrupt on rising edge of RB0/INT pin ; 0 = Interrupt on falling edge of RB0/INT pin ; bit 5: T0CS: TMR0 Clock Source Select bit ; 1 = Transition on RA4/T0CKI pin ; 0 = Internal instruction cycle clock (CLKOUT) ; bit 4: T0SE: TMR0 Source Edge Select bit ; 1 = Increment on high-to-low transition on RA4/T0CKI pin ; 0 = Increment on low-to-high transition on RA4/T0CKI pin ; bit 3: PSA: Prescaler Assignment bit ; 1 = Prescaler is assigned to the WDT ; 0 = Prescaler is assigned to the Timer0 module ; bit 2-0: PS2:PS0: Prescaler Rate Select bits, here shown for TMR0 : ; 000 = 1 : 2 ; ... 111 = 1 : 256 ; Note: to count EVERY pulse (1 : 1) with TMR0, the prescaler ; must be assigned to the WATCHDOG TIMER (WDT) ! ; Some examples (for the OPTION register, parameter in W for SetPrescaler): PSC_DIV_BY_2 equ b'00100000' ; let prescaler divide TMR0 by two PSC_DIV_BY_4 equ b'00100001' ; let prescaler divide TMR0 by 4 PSC_DIV_BY_8 equ b'00100010' ; let prescaler divide TMR0 by 8 PSC_DIV_BY_16 equ b'00100011' ; let prescaler divide TMR0 by 16 PSC_DIV_BY_32 equ b'00100100' ; let prescaler divide TMR0 by 32 PSC_DIV_BY_64 equ b'00100101' ; let prescaler divide TMR0 by 64 PSC_DIV_BY_128 equ b'00100110' ; let prescaler divide TMR0 by 128 PSC_DIV_BY_256 equ b'00100111' ; let prescaler divide TMR0 by 256 SetPrescaler: ; copy W into OPTION register, avoid watchdog trouble clrwdt ; recommended by Microchip ("switching prescaler assignment") errorlevel -302 ; Turn off banking message for the next few instructions.. bsf STATUS, RP0 ;! setting RP0 enables access to OPTION reg ; option register is in bank1. i know. thanks for the warning. movwf OPTION_REG ;! ex: "option" command (yucc) bcf STATUS, RP0 ;! clearing RP0 for normal register access errorlevel +302 ; Enable banking message again retlw 0 PrescalerOff: ; turn the prescaler for TMR0 "off" ; (actually done by assigning the prescaler to the watchdog timer) clrwdt ; clear watchdog timer clrf TMR0 ; clear timer 0 AND PRESCALER(!) errorlevel -302 ; Turn off banking message for the next few instructions.. bsf STATUS, RP0 ;! setting RP0 enables access to OPTION reg ; option register is in bank1. i know. thanks for the warning. movlw b'00100111' ;! recommended by Microchip when ;! changing prescaler assignment from TMR0 to WDT movwf OPTION_REG ;! ex: "option" command (yucc) clrwdt ;! clear watchdog again movlw b'00101111' ;! bit 3 set means PS assigned to WDT now movwf OPTION_REG ;! ex: "option" command (yucc) bcf STATUS, RP0 ;! clearing RP0 for normal register access errorlevel +302 ; Enable banking message again retlw 0 ;-------------------------------------------------------------------------- ; Power-saving subroutine: Puts the PIC to sleep for ROUGHLY 100 milliseconds . ; - crystal oscillator turned OFF during this phase ; - only the internal RC-oscillator for the watchdog keeps running ; - expiration of watchdog during sleep does NOT reset the PIC, ; only wakes it up again so normal operation may resume ; - LED display will be off during this time ;-------------------------------------------------------------------------- Sleep150ms: ; go to sleep for approx. 150 milliseconds, and then RETURN (no reset) ; Details on the PIC's watchdog timer (from PIC16F628 datasheet) : ; > The WDT has a nominal timeout period of 18 ms (with ; > no prescaler). The timeout periods vary with temperature, ; > VDD and process variations from part to part (see ; > DC specs). ; > The Watchdog Timer is a free running on-chip RC oscillator which does ; > not require any external components. This RC oscillator is separate ; > from the ER oscillator of the CLKIN pin. That means that the WDT will run, ; > even if the clock on the OSC1 and OSC2 pins of the device has been stopped, ; > for example, by execution of a SLEEP instruction. ; > During normal operation, a WDT timeout generates a device RESET. ; > If the device is in SLEEP mode, a WDT timeout causes the device to wake-up ; > and continue with normal operation. ; > The WDT can be permanently disabled by programming the configuration bit ; > WDTE as clear . ; In other words, to use the watchdog-timer for "temporary sleep" here , ; it must be ENABLED in the configuration word when programming the PIC. ; (because its not possible to turn it on via software if it's not on). ; But once the watchdog timer is ON, it must be FED periodically otherwise ; it will reset the PIC during normal operation ! ; Here (in the frequency counter), the prescaler remains assigned to timer0 ; so the watchdog interval is ~ 18 milliseconds (+/-, RC-oscillator) . ; > The CLRWDT and SLEEP instructions clear the WDT and the postscaler, ; > if assigned to the WDT, and prevent it from timing out and generating ; > a device RESET. The TO bit in the STATUS register will be cleared upon ; > a Watchdog Timer timeout. ; display with COMMON CATHODE : movlw 0x00 ; segment drivers LOW to turn off movwf LEDS_PORT ; turn LED segments off ; Note: The global interrupt-enable flag (GIE) is off in this application ! ; To avoid unintended wake-up on 'interrupt' (port level change), ; disable all interrupt-SOURCES: Clear T0IE,INTE,RBIE,PEIE too : clrf INTCON ; disable all interrupts during SLEEP mode clrwdt ; clear watchdog timer clrf TMR0 ; clear timer 0 AND PRESCALER(!) errorlevel -302 ; Turn off banking message for the next few instructions.. bsf STATUS, RP0 ;! setting RP0 enables access to OPTION reg ; option register is in bank1. i know. thanks for the warning. movlw b'00101011' ;! assign PS to WDT; divide by 8 FOR WDT(!) movwf OPTION_REG ;! ex: "option" command (yucc) bcf STATUS, RP0 ;! clearing RP0 for normal register access errorlevel +302 ; Enable banking message again sleep ; sleep for approx 18 ms (one watchdog interval) ; The SLEEP command clears the Watchdog Timer and stops the main oscillator. ; Only the internal watchdog timer keeps running. ; The WDT is is also cleared when the device wakes-up from SLEEP, ; regardless of the source of wake-up, so no need for 'clrwdt' here ! nop ; arrived here, slept for ~ 8 times 18 milliseconds return ; end Sleep150ms ;-------------------------------------------------------------------------- ; Convert a character into LEDs data for the 7-segment displays, fed with ; the character in w. Bit 7 set means 'decimal point AFTER this digit' . ;-------------------------------------------------------------------------- conv macro display ; macro for duplicate code movwf display ; save decimal point bit (msb) andlw 7fh ; mask bit call Digit2SevenSeg ; convert digit into 7-segment-code via table btfsc display,7 ; check bit 7 = decimal point ? iorlw 1<<DPPOINT_BIT ; include decimal point if bit 7 set (bitwise OR) movwf display ; set display data register endm conv_char0: ; display digit #0 (leftmost, or MOST SIGNIFICANT digit) conv display0 retlw 0 conv_char1: ; display #1 conv display1 retlw 0 conv_char2: ; display #2 conv display2 retlw 0 conv_char3: ; display #3 conv display3 retlw 0 conv_char4: ; display #4 (rightmost, or LEAST SIGNIFICANT digit, "ones") conv display4 retlw 0 ;-------------------------------------------------------------------------- ; Fill the 5-digit display latch with blank characters ;-------------------------------------------------------------------------- ClearDisplay: movlw BLANK_PATTERN movwf display0 movwf display1 movwf display2 movwf display3 movwf display4 retlw 0 ;-------------------------------------------------------------------------- ; Save a single Byte in the PIC's Data-EEPROM. ; Input parameters: ; INDF = *FSR contains byte to be written (was once EEDATA) ; w contains EEPROM address offset (i.e. "destination index") ; ;-------------------------------------------------------------------------- ; write to EEPROM data memory as explained in the 16F628 data sheet. ; EEDATA and EEADR must have been set before calling this subroutine ; (optimized for the keyer-state-machine). ; CAUTION : What the lousy datasheet DS40300B wont tell you: ; The example given there for the 16F628 is WRONG ! ; All EEPROM regs are in BANK1 for the 16F628. ; In the PIC16F84, some were in BANK0 others in BANK1.. ; In the PIC16F628, things are much different... all EEPROM regs are in BANK1 ! SaveInEEPROM: ; save "INDF" = *FSR in EEPROM[<w>] bcf INTCON, GIE ; disable INTs errorlevel -302 ; Turn off banking message for the next few instructions.. bsf STATUS, RP0 ;!; Bank1 for "EEADR" access, PIC16F628 ONLY (not F84) movwf EEADR ;!; write into EEPROM address register (BANK1 !!) bcf STATUS, RP0 ;!; Bank0 to read "bStorageData" movfw INDF ; ; w := *FSR (read source data from BANK 0) bsf STATUS, RP0 ;!; Bank1 for "EEDATA" access, PIC16F628 ONLY (not F84) movwf EEDATA ;!; EEDATA(in BANK1) := w (BANK1; F628 only, NOT F84 !!!) bsf EECON1, WREN ;!; set WRite ENable bcf INTCON, GIE ;!; Is this REALLY required as in DS40300B Example 13-2 ? movlw 055h ;!; movwf EECON2 ;!; write 55h movlw 0AAh ;!; movwf EECON2 ;!; write AAh bsf EECON1, WR ;!; set WR bit, begin write ; wait until write access to the EEPROM is complete. SaveEW: btfsc EECON1, WR ;!; WR is cleared after completion of write goto SaveEW ;!; WR=1, write access not finished yet ; Arrived here: the EEPROM write is ready bcf EECON1, WREN ;!; disable further WRites bcf STATUS, RP0 ;!; Bank0 for normal access errorlevel +302 ; Enable banking message again ; bsf INTCON, GIE ; enable INTs ? NOT IN THIS APPLICATION ! retlw 0 ; end SaveInEEPROM ;-------------------------------------------------------------------------- ; Read a single Byte from the PIC's Data-EEPROM. ; Input parameters: ; w contains EEPROM address offset (i.e. "source index") ; will *NOT* be modified to simplify block-read . ; FSR points to the memory location where the byte shall be placed. ; ; Result: ; INDF = *FSR returns the read byte ;-------------------------------------------------------------------------- ; Caution: EEDATA and EEADR have been moved from Bank0(16F84) to Bank1(16F628) ; and the example from the datasheet telling you to switch to ; bank0 to access EEDATA is rubbish (DS40300B page 93 example 13-1). EEPROM_ReadByte: ; read ONE byte from the PIC's data EEPROM movwf bTemp ; save W bcf INTCON, GIE ; disable INTs errorlevel -302 ; Turn off banking message for the next few instructions.. bsf STATUS, RP0 ; Bank1 for ***ALL*** EEPROM registers in 16F628 (!) movwf EEADR ;! write into EEPROM address register bsf EECON1, RD ;! set "Read"-Flag for EEPROM ; why is EECON1.RD not cleared in MPLAB-sim ?!? movf EEDATA, w ;! read byte from EEPROM latch bcf STATUS, RP0 ;! normal access to Bank0 errorlevel +302 ; Enable banking message again ; bsf INTCON, GIE ; re-enable interrupts ? NOT IN THIS APPLICATION ! movwf INDF ; place result in *FSR movfw bTemp ; restore W return ; back to caller ; end EEPROM_ReadByte EEPROM_Read4Byte: ; read FOUR bytes from the PIC's data EEPROM. ; Input parameters: ; w contains EEPROM address offset (i.e. "source index") ; will *NOT* be modified to simplify block-read . ; FSR points to the memory location where the byte shall be placed. call EEPROM_ReadByte ; *FSR = EEPROM[w] (usually bits 31..24) addlw 1 ; next source address incf FSR , f ; next destination address call EEPROM_ReadByte ; *FSR = EEPROM[w] (usually bits 23..16) addlw 1 ; next source address incf FSR , f ; next destination address call EEPROM_ReadByte ; *FSR = EEPROM[w] (usually bits 15..8) addlw 1 ; next source address incf FSR , f ; next destination address goto EEPROM_ReadByte ; *FSR = EEPROM[w] (usually bits 7..0) ; end EEPROM_Read4Byte ;-------------------------------------------------------------------------- ; Count pulses, fed with the number of loop iterations for the gate time . ; WHILE counting, the multiplexed LED display is updated . ; Watchdog is fed in this loop ! ; Input: Count of gate-time-loops in 'gatecnt_hi'+'gatecnt_lo' (16 bit). ; Returns: The number of pulses in 20us increments ; The number of periods measured (in pcnt) (added TheHWcave ) ; the sum of all measured periods in 20us increments (added TheHWcave ) ; in t0dark the number of pulses tmr0 counted outside this routine (added TheHWcave ) ; in t0last the last value of tmr0 when leaving this routine (added TheHWcave ) ;-------------------------------------------------------------------------- count_pulses: clrf freq_hi ; clear pulse counter (bits 31..24) clrf freq_mh ; bits 23..16 clrf freq_ml ; bits 15..8 clrf freq_lo ; bits 7..0 clrf period_hi ; clear period accumulator bits 8..15 clrf period_lo ; bits 0..7 clrf pcnt ; clear number of periods measured bcf PMODE_ON ; turn period conversion off by default ; until we are sure the input frequency ; is low enough for this to make sense clrf timer0_old ; 'old' value of timer0 to detect toggling MSB ; ; in counter mode, check if TMR0 moved since the last time and record ; the difference in t0dark movfw pmodeflag ; get current mode andlw 0x07 ; just the user selection sublw .4 btfsc STATUS,C goto count0 ; not in counter mode, proceed as normal ; ; calculate the number of pulses missed while being ouside this routine ; store the result in t0dark movfw TMR0 movwf t0dark movfw t0last subwf t0dark,f count0: clrf TMR0 ; timer register (PIC's hardware timer, 8 bit) nop ; 2 instruction cycle delay nop ; after writing to TMR0 (MPLAB-SIM: set breakpoint + clear stopwatch here) ; --------------- start of critial timing loop >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ; The following timing loop must take a well-defined time in total per ; iteration, usually 50 (or 20) microseconds, which can be precisely achieved ; with a 4-MHz-crystal (or 20 MHz for variant 2+3) . ; This gives a basic delay for the frequency counter's gate time . ; The frequency at the input of TIMER 0 (not the prescaler) ; can not exceed f_crystal / 4, ; and every HIGH->LOW transition of bit7 in TIMER0 must be polled here. ; This is safe because .. ; Variant 1: With a 4-MHz-crystal, Timer0 can count up to 1 MHz input, ; MSB toggles every (128/1MHz) = 128 us, polled every 50us -> ok. ; Variant 2: With a 20-MHz-crystal, Timer0 can count up to 4 (not 5?!) MHz input, ; MSB toggles every (128/4MHz) = 32 us, polled every 20us -> ok. ; The numbers in square brackets below are the INSTRUCTION NUMBER within the loop. ; (not the count of oscillator cycles for a single command, which is always 4). ; These values can be checked with the "Stopwatch" function in MPLAB-SIM. ; The goal is to let this loop take EXACTLY <TIME> microseconds (50us or 20us). count1 movfw disp_index ; [1] get the current digit number (disp_index = 0..4) call Digit2MuxValue ; [2,3,4,5,6,7] display (6 commands including call+retlw) movwf bTemp ; [8] save the bit pattern for the multiplexer port movlw display0 ; [9] get the LED display data for the current digit... addwf disp_index,w ; [10] add current digit number to address of LED data movwf FSR ; [11] move address into the PIC's poor 'data pointer' movfw INDF ; [12] w := *(FSR) use indirection register to read from table movwf LEDS_PORT ; [13] set the LED segments movfw bTemp ; [14] get the mupliplexer pattern (hurry, hurry !) movwf ENABLE_PORT ; [15] set the LED multiplexer incf disp_timer,f ; [16] increment display-multiplex timer btfsc disp_timer,6 ; [17] (6-bit prescaler) incf disp_index,f ; [18] next display if rolled over bcf disp_timer,6 ; [19] limit disp_timer to 6 bits (!) movfw disp_index ; [20] limit display index to 0...4 sublw .4 ; [21] subtract #4 - W register -> C=0(!) if result negative (W>4) btfss STATUS,C ; [22] skip next instruction if C=1 (#4-W >= 0) clrf disp_index ; [23] if C=0 (disp_index>4) then disp_index=0 ; the following fragments of code always take the same number of clock ; cycles to execute, irrespective of whether the skips take place or not . ; Here still in 'count_pulses'. movfw TMR0 ; [24] read least significant byte of movwf freq_lo ; [25] pulse counter (bits 7..0) movlw 1 ; [26] determine if timer 0 has rolled btfss timer0_old,7 ; [27] over (rolled over if msb was clrw ; [28] previously set and now isn't) btfsc freq_lo,7 ; [29] clrw ; [30] addwf freq_ml,f ; [31] increment high bytes of pulse counter skpnc ; [32] if low byte rolled over incf freq_mh,f ; [33] (mh = "medium high byte" of counter) ; NOTE: we are not modifying freq_hi here ! ; Bits 31..24 may be used later when multiplying with some factor ; (2^n) to compensate for the ASYNCHRON PRESCALER ! btfsc freq_mh,7 ; [34] overflow (freq > 7fffffh) ? goto count3 ; [35] branch if yes nop ; [36] nop ; [37] ;movfw freq_lo ; [36] save previous value from timer 0 ;movwf timer0_old ; [37] tstf gatecnt_lo ; [38] check inner gate-time counter, LOW byte skpnz ; [39] only decrement h-byte if l-byte zero decf gatecnt_hi,f ; [40] decrement gate-time counter, HIGH byte decf gatecnt_lo,f ; [41] always decrement gate-time counter, LOW byte ; 100 instruction cycles per loop ; (f_xtal=20 MHz, t_loop=20us, t_instr=4/20MHz=0.2us) ; clrwdt ; [42] (ex: nop, but since 2006-05-28 the dog must be fed !) ; ; TheHWcave: Measure period(s) in 20 uS units ; The original software aready kept a copy of the timer0 content ; at the previous loop, so we can use this to detect when the counter ; has changed. Because we are only interested in very low frequencies ; we can safely detect a single increment and there will be lots of loops ; with no change at all. The loop count (gatecnt) is counting down ; from 50000 (=1 second) and each count represents 20 us ; ; The idea is that if freq_lo changes to 1 we take copy of the gatecnt in pstart ; and for every subsequent frequency change, we calculate the difference between the current ; gatecnt and pstart which is the accumulated elapsed time (period) in 20 us units ; units. We also keep a counter pcnt to allow calculating the average period later ; for better resolution ; ; Note 1: We can only start measuring after the frequency counter value has reached ; 1 because the time from 0 to 1 is undetermined (the external signal is asynchronous) ; This means we need at least 1 Hz for this to produce period measurements. ; ; Note 2: This method could create a pcnt that can get too high for the subsequent 32-bit maths ; Therefore there is a check to stop accumulating periods and incrementing pcnt if ; 80 (in frequency mode) or 140 (in RPM) mode is reached ; ; ; movlw .10 ; [43] prepare to add 10x4 =40 wasted instructions later 50+40=90 movwf period_waste ; [44] movfw freq_lo ; [45] xorwf timer0_old,w ; [46] XOR of old and new counter. btfsc STATUS, Z ; [47] zero means no change goto P_done ; [48+1] ; movlw .1 ; [49] subwf freq_lo,w ; [50] btfss STATUS, Z ; [51] goto P_Measure ; [52+1] ; first transition: take a copy of the current gatecnt movfw gatecnt_lo ; [53] movwf pstart_lo ; [54] movfw gatecnt_hi ; [55] movwf pstart_hi ; [56] movlw .7 ; [57] prepare to add 7x4 =28 wasted instructions later 62+28=90 movwf period_waste ; [58] nop ; [59] goto P_done ; [60+1] ; subsequent transitions: (2, 3, 4..) calculate the accumulated elapsed time and copy to period P_Measure: movlw .6 ; [54] prepare to add 6x4 =24 wasted instructions later 66+24=90 movwf period_waste ; [55] ; ; check if pcnt has reached maximum. If yes, don't add amy further periods ; nop ; [56] movfw pmodeflag ; [57] are we in RPM or frequency mode? andlw 0x07 ; [58] btfss STATUS, Z ; [59] movlw .60 ; [60] RPM: pre-load W with 60 freq: W is already 0 addlw .80 ; [61] add 80: RPM W is 60+80=140 freq: W is 0+80 = 80 subwf pcnt,w ; [62] btfsc STATUS, C ; [63] goto P_done ; [64+1] stop if pcnt >= 80 (freq) or >= 140 (rpm) ; period = pstart - gatecnt (period=pstart; period=period-pstart ; movlw .2 ; [66] prepare to add 2x4 =8 wasted instructions later 82+8=90 movwf period_waste ; [67] movfw pstart_hi ; [68] movwf period_hi ; [69] movfw pstart_lo ; [70] movwf period_lo ; [71] bsf STATUS, C ; [72] ; 16-bit subtraction with carry movfw gatecnt_lo ; [73] btfss STATUS, C ; [74] incfsz gatecnt_lo,w ; [75] subwf period_lo,f ; [76] movfw gatecnt_hi ; [77] btfss STATUS, C ; [78] incfsz gatecnt_hi,w ; [79] subwf period_hi,f ; [80] ; incf pcnt,f ; [81] P_done: movf period_waste,w ; [50, 62, 66, 82 ] WasteT1: addlw 0xFF ; [51, .. ] btfss STATUS, Z ; [52, .. ] eats 4(!) INSTRUCTION CYCLES per loop goto WasteT1 ; [53+1 , .. ] ; Check this with MPLAB-SIM: here, after loop. below should always be [90] movfw freq_lo ; [90] save previous value from timer 0 movwf timer0_old ; [91] nop ; [92] nop ; [93] nop ; [94] nop ; [95] movfw gatecnt_hi ; [96] counter = 0 ? iorwf gatecnt_lo,w ; [97] skpz ; [98] goto count1 ; [99,50] goto always takes TWO instruction cycles ; <<<<<<<<<<<<<<<<<<<<<<<< end of timing loop ----------------------------- movfw TMR0 ; get final value from timer 0 movwf freq_lo movwf t0last ; save it for counter mode movlw 1 ; determine if timer 0 has rolled btfss timer0_old,7 ; over (rolled over if msb was clrw ; previously set and now isn't) btfsc freq_lo,7 clrw addwf freq_ml,f ; increment high bytes of pulse skpnc ; counter if low byte rolled incf freq_mh,f ; over count3 retlw 0 ; end of routine 'count_pulses'. Result now in freq_lo..freq_hi. ;-------------------------------------------------------------------------- ; Convert *FSR (32 bit) into BCD and show it on the display . ; Input : INDF = *FSR, 32-bit integer. ; Bad side effect : CONTENTS OF <freq> will be lost !! ;-------------------------------------------------------------------------- ShowInt32_FSR ; Convert <*FSR> (32 bit integer) to 8 BCD-digits ... movfw INDF ; W := *FSR , load LOW byte incf FSR , f ; FSR := FSR + 1 movwf freq ; freq.hi := W movfw INDF ; W := *FSR , load MIDDLE LOW byte incf FSR , f ; FSR := FSR + 1 movwf freq+1 ; freq.mh := W movfw INDF ; W := *FSR , load MIDDLE HIGH byte incf FSR , f ; FSR := FSR + 1 movwf freq+2 ; freq.ml := W movfw INDF ; W := *FSR , load HIGH byte incf FSR , f ; FSR := FSR + 1 movwf freq+3 ; freq.lo := W ; continue with CvtAndDisplayFreq ! ;-------------------------------------------------------------------------- ; Convert <freq> into BCD and show it on the display . ; Input : freq, 32-bit integer. CONTENTS OF <freq> will be lost !! ;-------------------------------------------------------------------------- CvtAndDisplayFreq ; Convert <freq>(32 bit integer) to 8 BCD-digits ... clrf tens_index ; initialise the table index movlw digits ; initialise the indirection register movwf FSR ; ( FSR="pointer"; *FSR=INDF) conv1 ; Loop for ALL POWERS OF TEN in the lookup table.. clrwdt ; feed the watchdog (may stay a bit longer) movfw tens_index ; fetch the next power of ten call TensTable ; (32 bits) from the lookup table movwf divi+0 ; and store in divi incf tens_index , f ; this was the HIGH byte movfw tens_index call TensTable movwf divi+1 incf tens_index , f ; this was the MIDDLE-HIGH byte movfw tens_index call TensTable movwf divi+2 incf tens_index , f ; this was the MIDDLE-LOW byte movfw tens_index call TensTable movwf divi+3 incf tens_index , f ; and this was the LOW-byte of a power of ten ; ex: clrf 0 ; clear the decimal digit .. but address ZERO is called 'INDF' these days ! clrf INDF ; *FSR = 0 conv2 ; Loop to repeatedly subtract divi from freq (32-bit subtract) ; until underflow while incrementing the decimal digit. sub32 freq,divi ; freq := freq - divi (with divi = 10 power N) bnc conv3 ; incf INDF , f ; The RESULT will be written back to freq, goto conv2 ; in other words 'freq' will be lost ! conv3 add32 freq,divi ; freq := freq+divi; ready for next digit incf FSR , f ; step to next decimal digit movlw 8*4 ; 8 x 4-byte entries in TensTable subwf tens_index,w bnz conv1 ; loop until end of table ;-------------------------------------------------------------------------- ; displays the frequency in decimal ;-------------------------------------------------------------------------- display_freq: ; Display the decimal digits according to the following rules ; 01234567 ; 00000Abc => 00A.bc 001.01 to 009.99 Hz Hz = decpoint at digit 5 ; 0000ABcd => 0AB.cd 010.01 to 099.99 Hz Hz = decpoint at digit 5 ; 00000ABC => 00.ABC 00.100 to 00.999 KHz kHz = decpoint at digit 4 ; 0000ABCD => 0A.BCD 01.000 to 09.999 KHz kHz = decpoint at digit 4 ; 000ABCDE => AB.CDE 10.000 to 99.999 KHz kHz = decpoint at digit 4 ; 00ABCDEF => ABC.DE 100.00 to 999.99 KHz 100KHz = decpoint at digit 4 ; 0ABCDEFG => A.BCDE 1.0000 to 9.9999 Mhz 1MHz = decpoint at digit 1 ; ABCDEFGH => AB.CDE 10.000 to 99.999 Mhz 10MHz = decpoint at digit 1 ; Modified a lot by WoBu to display kHz as well as MHz : ; If the decimal point means kHz, it flashes. ; If it means MHz, it is on permanently. ; 24 bit unsigned integer could count up to 16777216 (16 mio, slightly over 7 digits) ; which was not enough for a 50 MHz counter, so switched to 32-bit arithmetic . ; Modifed by TheHWcave to display Hz and fraction of Hz and RPM. It also does ; rounding to the final display resolution ; Display routine for frequencies up to "99.99 MHz" (theoretical): ; (do NOT insert the decimal point yet, ; it would disturb the blanking of LEADING zeroes ) movlw digits ; find the first significant digit.. movwf FSR ; .. by stepping over leading zeroes tstf INDF ; INDF = *(FSR) in "C" syntax, FSR points to 'digits' bnz displ_MHz ; 10-MHz-digit non-zero, show frequency in MHz incf FSR , f ; otherwise skip 1st digit (the 10-MHz place) tstf INDF bnz displ_MHz ; 1-MHz-digit non-zero, show frequency in MHz incf FSR , f ; otherwise skip 2nd digit (the 1-MHz place) tstf INDF bnz displ_100K ; 100-kHz-digit non-zero, show frequency in kHz (XXX.Xx) incf FSR , f ; otherwise skip 3rd digit (the 100-kHz place) ; 2018-03-23 (TheHWcave): modified to use the 5th digit for display ; variants #2 #3. For variant #1 the code is like it was ; NOTE: THE FSR content at this point needs to be preserved / restored ; before proceeding into the actual display... ; TheHWcave: If we are doing period measurement (freq or RPM), the ; digits 0..7 contain the desired value. displ_100K: btfss PMODE_ON goto displ_kHz ; go to normal display if not in period measurement mode movfw pmodeflag andlw 0x07 btfss STATUS, Z goto display ; >0 = RPM = no decimal needed displ_Hz: ; insert a STEADY POINT at digit 5 to indicate Hz + fractions bsf digit_5, 7 ; set the decimal point indicating the frequency in Hz . goto display displ_kHz: ; insert a BLINKING POINT to indicate the kilohertz-digit btfsc blinker, 0 ; check the blink flag (bit 0) for the kHz-point bsf digit_4, 7 ; set the decimal point indicating the frequency in kHz . goto display displ_MHz: ; insert a BLINKING POINT to indicate the kilohertz-digit bsf digit_1, 7 ; set the decimal point indicating the frequency in MHz . display: ; Show the FIVE digits beginning at INDF = *(FSR) on the LED display... movfw INDF ; convert the four digits to call conv_char0 ; LED display data incf FSR , f ; increment pointer to next digit movfw INDF ; w = *(FSR) call conv_char1 ; second visible digit incf FSR , f movfw INDF call conv_char2 ; third visible digit incf FSR , f movfw INDF call conv_char3 ; fourth visible digit incf FSR , f movfw INDF goto conv_char4 ; convert fifth visible digit AND RETURN ; end of routine "CvtAndDisplayFreq" ;-------------------------------------------------------------------------- ; main entry point ;-------------------------------------------------------------------------- MainInit: movlw PORT_A_IO ; initialise port A errorlevel -302 ; Turn off banking message for the next few instructions.. bsf STATUS, RP0 ;! setting RP0 enables access to TRIS regs movwf PORTA ;! looks like PORTA but is in fact TRISA bcf STATUS, RP0 ;! clearing RP0 enables access to PORTs clrf PORTA movlw PORT_B_IO ; initialise port B bsf STATUS, RP0 ;! setting RP0 enables access to TRIS regs movwf PORTB ;! looks like PORTB but is in fact TRISB bcf STATUS, RP0 ;! clearing RP0 enables access to PORTs errorlevel +302 ; Enable banking message again clrf PORTB clrf disp_index ; initialise display index and clrf disp_timer ; display multiplex timer movlw BLANK ; blank character as dummy ... movwf digit_8 ; for the lowest frequency display range ; movlw TEST ; test all LED segments ; call conv_char0 ; movlw TEST ; call conv_char1 ; movlw TEST ; call conv_char2 ; movlw TEST ; call conv_char3 ; movlw TEST ; call conv_char4 movlw PSC_DIV_BY_256 ; let the prescaler divide by 256 while testing.. call SetPrescaler ; safely write <W> into option register #if(DEBUG==1) ; Do a LAMP TEST for half a second, including all decimal points : movlw (LAMPTEST_LOOPS)>>8 ; high byte for 0.5 second lamp test movwf gatecnt_hi movlw (LAMPTEST_LOOPS)&0ffh ; low byte for 0.5 second lamp test movwf gatecnt_lo call count_pulses ; some delay to show the test pattern #endif ; not DEBUG MainRestart: ; Here we "restart" the counter after exiting from programming mode : clrf psave_timer ; clear timer for power-save mode (no immediate power-down) clrf psave_flags ; clear all power-saving flags (PSFLAG_ACTIVE, etc) ;movlw foffs ; load destination address for reading from EEPROM... ;movwf FSR ; ..into the PIC's pointer register ;movlw EEPROM_ADR_FREQ_OFFSET+0 ; load the EEPROM-internal address offset (=source index) ;call EEPROM_Read4Byte ; read from EEPROM: foffs..foffs+4 := EEPROM[W] movlw options ; another destination address for reading from EEPROM.. movwf FSR ; movlw EEPROM_ADR_OPTIONS ; load EEPROM-internal offset of "options"-byte call EEPROM_ReadByte ; read single byte from EEPROM: options := EEEPROM[W] ; Blank the display until 1st measurement is available : call ClearDisplay ; TheHWCave: We use the options variable which has been restored ; from EEPROM earlier, to store whether RPM or frequency ; should be displayed movfw options movwf pmodeflag SwitchMode: call show_mode movlw (LAMPTEST_LOOPS)>>8 ; high byte for 0.5 second lamp test movwf gatecnt_hi movlw (LAMPTEST_LOOPS)&0ffh ; low byte for 0.5 second lamp test movwf gatecnt_lo call count_pulses ; btfsc IOP_PROG_MODE ; check the switch goto SaveMode ; not pressed: save and go ... incf pmodeflag,f ; pressed: next setting movlw .6 subwf pmodeflag,w btfsc STATUS, Z clrf pmodeflag ; wrap around if necessary goto SwitchMode SaveMode: movfw pmodeflag movwf options movlw options ; .. and store in EEPROM movwf FSR movlw EEPROM_ADR_OPTIONS ; load EEPROM-internal offset of "options"-byte call SaveInEEPROM ;-------------------------------------------------------------------------- ; main loop : Preparation, auto ranging, measurement, conversion, display ;-------------------------------------------------------------------------- MainLoop: clrf freq2_hi ; clear counter (for counter mode) clrf freq2_mh ; bits 23..16 clrf freq2_ml ; bits 15..8 clrf freq2_lo ; bits 7..0 clrf t0dark clrf t0last ; re-initialise ports ; ex: tris PORTA; tris PORTB errorlevel -302 ; Turn off banking message for the next few instructions.. bsf STATUS, RP0 ;! setting RP0 enables access to TRIS regs movlw PORT_A_IO ;! movwf PORTA ;! looks like PORTA but is in fact TRISA movlw PORT_B_IO ;! movwf PORTB ;! looks like PORTB but is in fact TRISB bcf STATUS, RP0 ;! clearing RP0 enables access to PORTs clrwdt ; configure TMR0... but clear watchdog timer first movlw b'100000' ; value for OPTION reg: edge - low-to-high transition, ; + prescaler assigned to Timer 0, 1:2 bsf STATUS, RP0 ;! setting RP0 enables access to OPTION reg ; option register is in bank1. i know. thanks for the warning. movwf OPTION_REG ;! ex: "option" command (yucc) bcf STATUS, RP0 ;! clearing RP0 for normal register access errorlevel +302 ; Enable banking message again ; First do a 'range-detection measurement' to find ; a suitable prescaler ratio. Worst-case-estimation: ; 50 MHz at the input of the async TIMER 0 prescaler ; requires a prescaler ratio of 64 because ; the synchron counter in TIMER 0 accepts a maximum ; frequency of f_osc / 4, here: max. 1 MHz. ; The theoretic maximum frequency is 64 MHz then, which ; was almost reached when tested with a PIC 16F628 . ; The range-detection interval is somewhere near 1/30 seconds (see RANGE_DET_LOOPS), ; so frequencies below 30*64 = 1920 Hz are not detectable at this step. RANGE_DET_LOOPS equ CLOCK/(.30*CYCLES) ; number of gate-time loops to detect the MEASURING RANGE ; (which is required to find a good prescaler value) movlw (RANGE_DET_LOOPS)>>8 ; high byte for RANGE DETECTION loop counter movwf gatecnt_hi movlw (RANGE_DET_LOOPS)&0ffh ; low byte for RANGE DETECTION loop counter movwf gatecnt_lo movlw PSC_DIV_BY_64 ; let the prescaler divide by 64 while testing.. call SetPrescaler ; safely write <W> into option register call count_pulses ; count pulses for the range detection interval (1/16 sec) ; The result will be placed in freq_lo,freq_ml,freq_mh,freq_hi (32 bit) ; but the max count at 64 MHz input, 1/30 sec gate time, and prescaler=64 will be : ; 64MHz / (30 * 64) = 33333 pulses, so only 16 bits in the counter ; are required here (call them "testcount", f_in = testcount * 30*64) . ; The frequency resolution of this coarse measurement is 64*16 Hz = roughly 1 kHz. ; (for that reason it's not suited for "wake-up from power-save on frequency-change") ; Load the default (soft-)counters for the GATE TIME. ; Most measuring ranges use a 1/4 second gate time ! movlw (GATE_TIME_LOOPS/4)>>8 ; high byte of gate time movwf gatecnt_hi movlw (GATE_TIME_LOOPS/4)&0ffh ; low byte of gate time movwf gatecnt_lo ; Increment the "blinker" once every 0.25 seconds. ; (if the gate time is longer, flashing will be slower, that's acceptable) incf blinker, f incf psave_timer, f ; increment the power-save timer every 0.25 seconds too (checked somewhere else) ; Look at the range-detection count ("testcount") ; and decide which measuring range to use, beginning with the highest frequency range ; Ranges FOR 20 MHz CRYSTAL (draws more power, but gives better resolution at HF ) ; Even if PIC clocked with 20MHz, keep the input of TIMER0 below 4(!) MHz . ; Rng testcount f_in prescaler gate_time display, resolution ; (1) 0..6 0.. 11.5 kHz 1 1 second X.XXXkHz, 0.001kHz (4 digits only) ; (2) 7..54 ..103.6 kHz 1 1/2 second XX.XXXkHz, 0.002kHz (last digit steps by 2) ; (3) 44..2047 .. 3.9 MHz 1 1/4 second X.XXXXMHz, 4 Hz (last digit steps by 1) ; (4) 2048..4095 .. 7.9 MHz 2 1/4 second X.XXXXMHz, 8 Hz (last digit steps by 1) ; (5) 4096..8191 ... 15.7 MHz 4 1/4 second X.XXXXMHz, 16 Hz (last digit steps by 1) ; (6) 8192..16383 ... 31.4 MHz 8 1/4 second X.XXXXMHz, 32 Hz (last digit steps by 1 or 2) ; (7) 16384..33330 ... 63.9 MHz 16 1/4 second XX.XXXMHz, 64 Hz (last digit steps by 1) movfw freq_ml ; first look at bits 15..8 of the 'test count' result andlw b'11000000' ; any of bits 15..14 set (>=16384) -> no Z flag -> range 7 btfss STATUS,Z ; skip next instruction if ZERO-flag set (!) goto Range7 ; far jump to range 7 btfsc freq_ml,5 ; bit 13 set (>=8192) -> range 6 goto Range6 btfsc freq_ml,4 ; bit 12 set (>=4096) -> range 5 goto Range5 btfsc freq_ml,3 ; bit 11 set (>=2048) -> range 4 goto Range4 btfsc freq_ml,2 ; bit 10 set (>=1024) -> range 3 goto Range3 btfsc freq_ml,1 ; bit 9 set (>=512) -> range 3 goto Range3 btfsc freq_ml,0 ; bit 8 set (>=256) -> no Z flag -> range 3 goto Range3 movfw freq_lo ; now look at bits 7..0 only .. sublw .54 ; subtract #54 - W register -> C=0 if result negative btfss STATUS,C ; skip next instruction if C=1 (#54-W >= 0) goto Range3 ; freq > 100kHz -> also range 3 movfw freq_lo ; look at bits 7..0 again .. sublw .5 ; subtract #5 - W register -> C=0 if result negative ; ----------- ; 2018-03-23 (TheHWcave): Disable the next 2 instructions to always use 1Hz ; resolution in the range up to 105600 Hz ;btfss STATUS,C ; skip next instruction if C=1 ;goto Range2 ; freq > 10kHz -> range 2 goto Range1 ; otherwise range 1 (lowest frequencies) Range1: ; Range 1: async prescaler off, 1 second gate time for very low frequencies : call PrescalerOff ; turn hardware prescaler off incf psave_timer, f ; increment power-save timer three more times incf psave_timer, f ; (1 sec-gate instead of 0.25) incf psave_timer, f ; Load the GATE TIMER (as count of loops) for this measuring range. movlw (GATE_TIME_LOOPS)>>8 ; high byte for 1 second gate time movwf gatecnt_hi movlw (GATE_TIME_LOOPS)&0ffh ; low byte for 1 second gate time movwf gatecnt_lo ; Load the count of "left shifts" to compensate gate time + prescaler : movlw 0 ; no need to multiply with prescaler 1:1 and 1-sec gate time goto GoMeasure Range2: ; Range 2: async prescaler off, 1/2 second gate time for quite low frequencies : call PrescalerOff ; turn hardware prescaler off incf psave_timer, f ; increment power-save timer one more time (0.5 sec-gate instead of 0.25) ; Load the GATE TIMER (as count of loops) for this measuring range. movlw (GATE_TIME_LOOPS/2)>>8 ; high byte for 1/2 second gate time movwf gatecnt_hi movlw (GATE_TIME_LOOPS/2)&0ffh ; low byte for 1/2 second gate time movwf gatecnt_lo ; Load the count of "left shifts" to compensate gate time + prescaler : movlw 1 ; multiply by 2 (=2^1) later to compensate gate time (1/2 s) goto GoMeasure Range3: ; Range 3: async prescaler off, gate time = default (1/4 sec) : call PrescalerOff ; turn hardware prescaler off movlw 2 ; multiply by 4 (=2^2) later to compensate gate time (1/4 s) goto GoMeasure Range4: ; Range 4: prescaler divide by 2 , gate time = default (1/4 sec) : movlw PSC_DIV_BY_2 ; let the prescaler divide by 2 while MEASURING... call SetPrescaler ; safely write <W> into option register movlw 3 ; multiply by 8 (=2^3) later to compensate prescaling (1:2) * gate time (1/4 s) goto GoMeasure Range5: ; Range 5: prescaler divide by 4 , gate time = default (1/4 sec) : movlw PSC_DIV_BY_4 ; let the prescaler divide by 2 while MEASURING... call SetPrescaler ; safely write <W> into option register movlw 4 ; multiply by 16 (=2^4) later to compensate prescaling (1:4) * gate time (1/4 s) goto GoMeasure Range6: ; Range 6: prescaler divide by 8 , gate time = default (1/4 sec) : movlw PSC_DIV_BY_8 ; let the prescaler divide by 2 while MEASURING... call SetPrescaler ; safely write <W> into option register movlw 5 ; multiply by 32 (=2^5) later to compensate prescaling (1:8) * gate time (1/4 s) goto GoMeasure Range7: ; Range 7: prescaler divide by 16 , gate time = default (1/4 sec) : movlw PSC_DIV_BY_16 ; let the prescaler divide by 2 while MEASURING... call SetPrescaler ; safely write <W> into option register movlw 6 ; multiply by 64 (=2^6) later to compensate prescaling (1:16) * gate time (1/4 s) goto GoMeasure GoMeasure: movwf adjust_shifts ; save the number of "arithmetic left shifts" for later ; ; TheHWcave:check for counter mode ; movfw pmodeflag ; get current mode andlw 0x07 ; just the user selection sublw .4 BC GoMeasure1 ; not in counter mode MainLoopCnt: ; we are in counter mode ; Load the GATE TIMER (as count of loops) for this measuring range. movlw (GATE_TIME_LOOPS/.10)>>8 ; high byte for 1/10 second gate time movwf gatecnt_hi movlw (GATE_TIME_LOOPS/.10)&0ffh ; low byte for 1/10 second gate time movwf gatecnt_lo call count_pulses ; count pulses for 1/10s ; Result in freq_lo,freq_ml,freq_mh,freq_hi (32 bit) now addx32 freq,freq2 ; freq2 = freq2 + freq ; ; add any counts that happened during "dark time" movfw t0dark movwf freq_lo clrf freq_ml clrf freq_mh clrf freq_hi addx32 freq,freq2 ; freq2 = freq2 + freq ; copy result back into freq for display movfw freq2_hi movwf freq_hi movfw freq2_mh movwf freq_mh movfw freq2_ml movwf freq_ml movfw freq2_lo movwf freq_lo ; check for overflow 100000 = 0x0186A0 ; if so, reset counter movfw freq_mh sublw 0x01 BNC cntreset ; >= 0x02xxxx = must reset BNZ cntvalid ; <= 0x00xxxx = ok movfw freq_ml sublw 0x86 BNC cntreset ; >= 0x0187xx = must reset BNZ cntvalid ; <= 0x0185xx = ok movfw freq_lo sublw 0x9F BNC cntreset ; >= 0x0186A0 = must reset cntvalid: call CvtAndDisplayFreq ; btfsc IOP_PROG_MODE ; check the switch goto MainLoopCnt ; not pressed: keep counting... cntreset: clrf freq2_hi ; reset counter clrf freq2_mh ; bits 23..16 clrf freq2_ml ; bits 15..8 clrf freq2_lo ; bits 7..0 clrf t0dark clrf t0last goto MainLoopCnt ; GoMeasure1: ; measure frequency or RPM call count_pulses ; count pulses for 1, 1/2, or 1/8 s . ; Result in freq_lo,freq_ml,freq_mh,freq_hi (32 bit) now, ; NOT adjusted for the gate-time or prescaler division ratio yet. PsNotBlanked: ; Display is not blanked for power-saving mode at the moment. ; If this 'absolute difference' is quite large, ; clear the power-save timer to prevent turning off the display ; within the next XX seconds : ; Reload the power-save-timer if there was a significant change ; since the last comparison. PrepDisp: ; Prepare the frequency (32-bit 'unadjusted' integer) for display: ; Multiply freq by 2^adjust_shifts to adjust for the prescaling ; and the timing period . The result will be a frequency in HERTZ, 32-bit integer. ; Note: the adjustment factor may be ONE which means no shift at all. tstf adjust_shifts bz NoAdjust Adjust: clrc rlf freq_lo , f rlf freq_ml , f rlf freq_mh , f rlf freq_hi , f decfsz adjust_shifts, f goto Adjust NoAdjust: ; Check the result against under- and overflow. ; (There should be none if the frequency didn't change too rapidly ; between the range-detection and the actual measurement ) movfw freq_hi ; underflow (freq = 0) ? iorwf freq_mh,w iorwf freq_ml,w iorwf freq_lo,w bz freq_underflow ; branch if yes btfsc freq_hi,7 ; overflow (freq > 7FFfffffh) ? goto freq_overflow ; branch if yes ; for debugging the maths ;movlw 0x5f ; ;movwf period_hi ;movlw 0x62 ;movwf period_lo ;movlw .44 ;movwf pcnt ;bcf PMODE_RPM ; TheHWcave: This section screens out any frequencies that ; would cause problems or inaccurate calculations ; We only accept frequencies <= 200Hz in frequency mode, ; or < 256 Hz in RPM mode movf freq_hi,w iorwf freq_mh,w iorwf freq_ml,w BNZ F_Hirange ; frequencies > 255 Hz go to extended RPM range check ; frequency is <= 255 Hz. ; movfw pmodeflag andlw 0x07 btfss STATUS, Z goto P_Zero movlw .201 subwf freq_lo,w BC F_Hirange ; frequency > 200 Hz ; P_Zero: movf pcnt,f ; zero periods? This could happen at very low btfss STATUS, Z ; .. freqencies < 2Hz. goto P_Conv ; .. we must avoid dividing by zero movlw .1 ; .. by preset to 1 x 1s period = 1Hz movwf pcnt movlw (ONESECOND>>8) & 0xff movwf period_hi movlw ONESECOND & 0xff movwf period_lo ; TheHWcave: This section adjusts the conversion factor for the number ; of periods we have measured. When we later divide by the ; sum of the measured periods, we effectively average ; across the number of periods ; ; conversion = conversion * number_of_periods (pcnt) ; ; the conversion factor depends on whether we are displaying ; frequencies or RPMx1 RPMx2 or RPMx3 ; ; the multiplication is done by repeated adding and it gets ; big, so 32-bit mode is needed ; ; P_Conv: clrf freq_hi ; we re-use the frequency buffer for the 32-bit result clrf freq_mh ; .. but need to clear it first clrf freq_ml clrf freq_lo movfw pmodeflag andlw 0x07 btfss STATUS, Z goto P_RPM1 ; ; Frequency mode movlw (PERIOD2FREQ >> .24) & 0xff ; load the conversion for frequency movwf freq2_hi movlw (PERIOD2FREQ >> .16) & 0xff movwf freq2_mh movlw (PERIOD2FREQ >> .8) & 0xff movwf freq2_ml movlw PERIOD2FREQ & 0xff movwf freq2_lo goto P_Mul P_RPM1: addlw 0xFF ; decrement w btfss STATUS, Z goto P_RPM2 movlw (PERIOD2RPM_1 >> .24) & 0xff ; load the conversion for RPM1 movwf freq2_hi movlw (PERIOD2RPM_1 >> .16) & 0xff movwf freq2_mh movlw (PERIOD2RPM_1 >> .8) & 0xff movwf freq2_ml movlw PERIOD2RPM_1 & 0xff movwf freq2_lo goto P_Mul P_RPM2: addlw 0xFF ; decrement w btfss STATUS, Z goto P_RPM3 movlw (PERIOD2RPM_2 >> .24) & 0xff ; load the conversion for RPM2 movwf freq2_hi movlw (PERIOD2RPM_2 >> .16) & 0xff movwf freq2_mh movlw (PERIOD2RPM_2 >> .8) & 0xff movwf freq2_ml movlw PERIOD2RPM_2 & 0xff movwf freq2_lo goto P_Mul P_RPM3: addlw 0xFF ; decrement w btfss STATUS, Z goto P_RPM4 movlw (PERIOD2RPM_3 >> .24) & 0xff ; load the conversion for RPM3 movwf freq2_hi movlw (PERIOD2RPM_3 >> .16) & 0xff movwf freq2_mh movlw (PERIOD2RPM_3 >> .8) & 0xff movwf freq2_ml movlw PERIOD2RPM_3 & 0xff movwf freq2_lo goto P_Mul P_RPM4: movlw (PERIOD2RPM_4 >> .24) & 0xff ; load the conversion for RPM3 movwf freq2_hi movlw (PERIOD2RPM_4 >> .16) & 0xff movwf freq2_mh movlw (PERIOD2RPM_4 >> .8) & 0xff movwf freq2_ml movlw PERIOD2RPM_4 & 0xff movwf freq2_lo P_Mul: addx32 freq2, freq ; freq = freq + freq2 decf pcnt,f btfss STATUS, Z goto P_Mul ; TheHWcave: This section divides the adjusted conversion factor by the ; sum of the periods. This is a 32-bit divided by 16-bit ; operation using repeated 32-bit subtraction. The result is ; a 24-bit number which is the desired frequency (in millihertz) ; or RPM (in tens of RPM). ; ; This calculation takes so much time that the watchdog timer ; would trigger and because the display multiplexing is stopped ; the last digit would be extremly bright and destroy the display ; I tried turning the display off, which works but causes a very ; irritating blinking display. So .. there is no choice, we have ; to keep multiplexing the display during the division which ; makes the calculation even slower.. clrf freq2_hi clrf freq2_mh movfw period_hi movwf freq2_ml movfw period_lo movwf freq2_lo clrf pdiv_mh clrf pdiv_ml clrf pdiv_lo P_Div: call RefreshDisplay subx32 freq2, freq ; freq = freq - freq2 btfss STATUS, C goto P_DivEnd incf pdiv_lo,f btfsc STATUS, Z incf pdiv_ml,f btfsc STATUS, Z incf pdiv_mh,f goto P_Div P_DivEnd: clrf freq_hi ; copy the result back into the freq_xx variable movfw pdiv_mh ; movwf freq_mh ; movfw pdiv_ml movwf freq_ml movfw pdiv_lo movwf freq_lo bsf PMODE_ON ; switch display format goto F_Display ; TheHWcave: for extended range RPM1, 2 or 3 we are using the frequency ; not the period. The multiplier is 60, 30, or 20 ; ; Because the multiply loop starts adding the already loaded frequency ; to itself the factor needs to be one less (because without doing ; anything we would have effectively already multiplied by 1 ; F_Hirange: movfw pmodeflag andlw 0x07 BZ F_Display ; frequency mode: no need to do anything more addlw 0xFF ; decrement w BZ P_RPMX1 addlw 0xFF ; decrement w BZ P_RPMX2 addlw 0xFF ; decrement w BZ P_RPMX3 ; must be RPM4 movlw FREQ2RPM_4 -.1 ; RPM_4 multiplier movwf pcnt movlw 0x17 +.1 ; max range 0x17ff = 6143 Hz = 92145 RPM goto P_RPMX P_RPMX3: ; RPM3 movlw FREQ2RPM_3 -.1 ; RPM_3 multiplier movwf pcnt movlw 0x11 +.1 ; max range 0x11ff = 4607 Hz = 92140 RPM goto P_RPMX P_RPMX2: ; RPM2 movlw FREQ2RPM_2 -.1 ; RPM_2 multiplier movwf pcnt movlw 0x0b + .1 ; max range 0x0bff = 3071 Hz = 92130 RPM goto P_RPMX P_RPMX1: ; RPM1 movlw FREQ2RPM_1 -.1 ; RPM_1 multiplier movwf pcnt movlw 0x05 +.1 ; max range 0x05ff = 1535 Hz = 92100 RPM ; P_RPMX: subwf freq_ml,w ; test range BC F_Display ; zero or positive = out of range ; in range: multiply frequency (8 bit * 32 bit ) clrf freq2_hi clrf freq2_mh movfw freq_ml movwf freq2_ml movfw freq_lo movwf freq2_lo P_Mulx: addx32 freq2, freq ; freq = freq + freq2 decf pcnt,f BNZ P_Mulx bsf PMODE_ON ; switch display format to "fake" period measurement result F_Display: call CvtAndDisplayFreq ; Convert <freq> into BCD and show it on the display goto MainLoop ; end of main loop RefreshDisplay: ; TheHWCave: This is a straight copy from the timing loop ; except the watchdog timer is included as well ; movfw disp_index ; [1] get the current digit number (disp_index = 0..4) call Digit2MuxValue ; [2,3,4,5,6,7] display (6 commands including call+retlw) movwf bTemp ; [8] save the bit pattern for the multiplexer port movlw display0 ; [9] get the LED display data for the current digit... addwf disp_index,w ; [10] add current digit number to address of LED data movwf FSR ; [11] move address into the PIC's poor 'data pointer' movfw INDF ; [12] w := *(FSR) use indirection register to read from table movwf LEDS_PORT ; [13] set the LED segments movfw bTemp ; [14] get the mupliplexer pattern (hurry, hurry !) movwf ENABLE_PORT ; [15] set the LED multiplexer incf disp_timer,f ; [16] increment display-multiplex timer btfsc disp_timer,6 ; [17] (6-bit prescaler) incf disp_index,f ; [18] next display if rolled over bcf disp_timer,6 ; [19] limit disp_timer to 6 bits (!) movfw disp_index ; [20] limit display index to 0...4 sublw .4 ; [21] subtract #4 - W register -> C=0(!) if result negative (W>4) btfss STATUS,C ; [22] skip next instruction if C=1 (#4-W >= 0) clrf disp_index ; [23] if C=0 (disp_index>4) then disp_index=0 clrwdt ; feed the dog retlw 0 ; TheHWCave: Load the display with the current mode (freq / rpm / counter) show_mode: movfw pmodeflag ; get current mode andlw 0x07 ; just the user selection btfsc STATUS, Z goto sm_freq ; if zero = it was freq sublw .4 BNC sm_count ; if >= 5 : counter mode movlw CHAR_r ; preset with "rP=__" call conv_char0 movlw CHAR_P call conv_char1 movlw CHAR_EQ call conv_char2 movlw BLANK ; leave blank for now call conv_char3 movlw BLANK call conv_char4 movfw pmodeflag ; get current mode andlw 0x07 ; just the user selection call conv_char3 ; set to "rP=x " retlw 0 sm_freq: movlw CHAR_F call conv_char0 ; set to "FrEq" movlw CHAR_r call conv_char1 movlw CHAR_E call conv_char2 movlw CHAR_Q call conv_char3 movlw BLANK call conv_char4 retlw 0 sm_count: movlw CHAR_c call conv_char0 ; set to "couNt" movlw CHAR_o call conv_char1 movlw CHAR_u call conv_char2 movlw CHAR_N call conv_char3 movlw CHAR_t call conv_char4 retlw 0 ;-------------------------------------------------------------------------- ; frequency underflow (frequency < 1Hz) ;-------------------------------------------------------------------------- freq_underflow: movlw BLANK ; display underflow as " 0[0]" call conv_char0 movlw BLANK call conv_char1 movlw BLANK call conv_char2 ; 2018-03-23 (TheHWcave): modified to use the 5th digit for display ; variants #2 #3. For variant #1 the code is like it was movlw BLANK ; call conv_char3 movlw 0 call conv_char4 ; use the 5th digit because its there ! goto MainLoop ;-------------------------------------------------------------------------- ; frequency overflow (frequency > 50MHz) ;-------------------------------------------------------------------------- freq_overflow: movlw BLANK ; display overflow as " E" call conv_char0 movlw BLANK call conv_char1 movlw BLANK call conv_char2 ; 2018-03-23 (TheHWcave): modified to use the 5th digit for display ; variants #2 #3. For variant #1 the code is like it was movlw BLANK ; call conv_char3 movlw CHAR_E call conv_char4 ; use the 5th digit because its there ! goto MainLoop ; end of main loop ; END ; directive 'end of program'
// Thomas Lowe, 2020. // Generates one of the cross family of structures. #include <fstream> #include "stdafx.h" // Change this parameter for cross structures with different numbers of sides. static int sides = 5; // Controls the detail level static int numIterations = 7; namespace { struct CrossSection { Vector2d pos; Vector2d up; void expand(); void draw(ofstream &svg, const Vector2d &origin); public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; } static double scale = 750.0; static Vector2d offset(1.0, 0.5); static vector<Vector2d> tri; static void saveSVG(const string &fileName, const vector<CrossSection, aligned_allocator<CrossSection> > &list) { static ofstream svg; svg.open(fileName.c_str()); svg << "<svg width = \"" << (int)(2.0*scale) << "\" height = \"" << (int)scale << "\" xmlns = \"http://www.w3.org/2000/svg\">" << endl; for (auto &sec : list) { Vector2d side(sec.up[1], -sec.up[0]); for (int i = 0; i < (int)tri.size(); i++) { Vector2d end = sec.pos + tri[i][0] * side + tri[i][1] * sec.up; svg << "<path d = \"M " << scale*(sec.pos[0] + offset[0]) << " " << scale - scale*(sec.pos[1] + offset[1]); svg << " L " << scale*(end[0] + offset[0]) << " " << scale - scale*(end[1] + offset[1]); svg << "\" stroke=\"black\" stroke-width=\"1\" />\n"; } } svg << "</svg>" << endl; svg.close(); } static vector<CrossSection, aligned_allocator<CrossSection> > transform(vector<CrossSection, aligned_allocator<CrossSection> > &list, const Vector2d &translation) { vector<CrossSection, aligned_allocator<CrossSection> > newChild = list; for (int i = 0; i < (int)newChild.size(); i++) { newChild[i].pos = -newChild[i].pos + translation; newChild[i].up = -newChild[i].up; } return newChild; } int chapter3Figure12() { for (int i = 0; i < sides; i++) { double angle = (double)i * 2.0*pi / (double)sides; tri.push_back(2.0 * Vector2d(sin(angle), cos(angle))); } vector<CrossSection, aligned_allocator<CrossSection> > list(1); list[0].pos = Vector2d(0, 0); double scl = 0.005; list[0].up = Vector2d(0, scl); vector<Vector2d> ends(sides); for (int i = 0; i<sides; i++) ends[i] = tri[i] * scl; for (int j = 0; j < numIterations; j++) { vector<CrossSection, aligned_allocator<CrossSection> > newList; vector<Vector2d> newEnds(sides); for (int i = 0; i < sides; i++) { vector<CrossSection, aligned_allocator<CrossSection> > newChild = transform(list, ends[i]); newList.insert(newList.end(), newChild.begin(), newChild.end()); newEnds[i] = -ends[(i + (sides/2)) % sides] + ends[i]; } list = newList; for (int i = 0; i < sides; i++) ends[i] = newEnds[i]; } if (sides == 3) saveSVG("fudgeflake.svg", list); else if (sides == 4) saveSVG("greekcross.svg", list); else if (sides == 5) saveSVG("pentacross.svg", list); else if (sides == 6) saveSVG("hexacross.svg", list); return 0; }
//.............................. // UI Lab Inc. Arthur Amshukov . //.............................. #ifndef __ARCTURUS_PARSE_CONTEXT_H__ #define __ARCTURUS_PARSE_CONTEXT_H__ #pragma once BEGIN_NAMESPACE(arcturus) USING_NAMESPACE(core) USING_NAMESPACE(frontend) class arcturus_parse_context : public parse_context { public: using tree_type = typename parse_context::tree_type; private: // extra data public: arcturus_parse_context(); virtual ~arcturus_parse_context(); }; END_NAMESPACE #endif // __ARCTURUS_PARSE_CONTEXT_H__
object_const_def ; object_event constants const OLIVINELIGHTHOUSE2F_SAILOR const OLIVINELIGHTHOUSE2F_GENTLEMAN OlivineLighthouse2F_MapScripts: db 0 ; scene scripts db 0 ; callbacks TrainerGentlemanAlfred: trainer GENTLEMAN, ALFRED, EVENT_BEAT_GENTLEMAN_ALFRED, GentlemanAlfredSeenText, GentlemanAlfredBeatenText, 0, .Script .Script: endifjustbattled opentext writetext GentlemanAlfredAfterBattleText waitbutton closetext end TrainerSailorHuey: trainer SAILOR, HUEY1, EVENT_BEAT_SAILOR_HUEY, SailorHueySeenText, SailorHueyBeatenText, 0, .Script .Script: loadvar VAR_CALLERID, PHONE_SAILOR_HUEY endifjustbattled opentext checkflag ENGINE_HUEY iftrue .WantsBattle checkcellnum PHONE_SAILOR_HUEY iftrue .NumberAccepted checkevent EVENT_HUEY_ASKED_FOR_PHONE_NUMBER iftrue .AskedBefore setevent EVENT_HUEY_ASKED_FOR_PHONE_NUMBER scall .AskNumber1 sjump .AskForNumber .AskedBefore: scall .AskNumber2 .AskForNumber: askforphonenumber PHONE_SAILOR_HUEY ifequal PHONE_CONTACTS_FULL, .PhoneFull ifequal PHONE_CONTACT_REFUSED, .NumberDeclined gettrainername STRING_BUFFER_3, SAILOR, HUEY1 scall .RegisteredNumber sjump .NumberAccepted .WantsBattle: scall .Rematch winlosstext SailorHueyBeatenText, 0 readmem wHueyFightCount ifequal 3, .Fight3 ifequal 2, .Fight2 ifequal 1, .Fight1 ifequal 0, .LoadFight0 .Fight3: checkevent EVENT_RESTORED_POWER_TO_KANTO iftrue .LoadFight3 .Fight2: checkevent EVENT_BEAT_ELITE_FOUR iftrue .LoadFight2 .Fight1: ; checkevent EVENT_CLEARED_RADIO_TOWER ; iftrue .LoadFight1 .LoadFight0: loadtrainer SAILOR, HUEY1 startbattle reloadmapafterbattle loadmem wHueyFightCount, 1 clearflag ENGINE_HUEY end .LoadFight1: loadtrainer SAILOR, HUEY2 startbattle reloadmapafterbattle loadmem wHueyFightCount, 2 clearflag ENGINE_HUEY end .LoadFight2: loadtrainer SAILOR, HUEY3 startbattle reloadmapafterbattle loadmem wHueyFightCount, 3 clearflag ENGINE_HUEY end .LoadFight3: loadtrainer SAILOR, HUEY4 startbattle reloadmapafterbattle clearflag ENGINE_HUEY checkevent EVENT_HUEY_PROTEIN iftrue .HasProtein checkevent EVENT_GOT_PROTEIN_FROM_HUEY iftrue .SkipGift scall .RematchGift verbosegiveitem PROTEIN iffalse .PackFull setevent EVENT_GOT_PROTEIN_FROM_HUEY sjump .NumberAccepted .SkipGift: end .HasProtein: opentext writetext SailorHueyGiveProteinText waitbutton verbosegiveitem PROTEIN iffalse .PackFull clearevent EVENT_HUEY_PROTEIN setevent EVENT_GOT_PROTEIN_FROM_HUEY sjump .NumberAccepted .AskNumber1: jumpstd asknumber1m end .AskNumber2: jumpstd asknumber2m end .RegisteredNumber: jumpstd registerednumberm end .NumberAccepted: jumpstd numberacceptedm end .NumberDeclined: jumpstd numberdeclinedm end .PhoneFull: jumpstd phonefullm end .Rematch: jumpstd rematchm end .PackFull: setevent EVENT_HUEY_PROTEIN jumpstd packfullm end .RematchGift: jumpstd rematchgiftm end SailorHueySeenText: text "Men of the sea are" line "always spoiling" cont "for a good fight!" done SailorHueyBeatenText: text "Urf!" line "I lose!" done SailorHueyUnusedText: ; unused text "What power!" line "How would you like" para "to sail the seas" line "with me?" done GentlemanAlfredSeenText: text "Hm? This is no" line "place for playing." done GentlemanAlfredBeatenText: text "Ah! I can see that" line "you're serious." done GentlemanAlfredAfterBattleText: text "Up top is a #-" line "MON that keeps the" cont "LIGHTHOUSE lit." para "But I hear that" line "it's sick now and" para "can't be cured by" line "ordinary medicine." done SailorHueyGiveProteinText: text "Man! You're as" line "tough as ever!" para "Anyway, here's" line "that medicine from" cont "before." done OlivineLighthouse2F_MapEvents: db 0, 0 ; filler db 6 ; warp events warp_event 3, 11, OLIVINE_LIGHTHOUSE_1F, 3 warp_event 5, 3, OLIVINE_LIGHTHOUSE_3F, 2 warp_event 16, 13, OLIVINE_LIGHTHOUSE_1F, 4 warp_event 17, 13, OLIVINE_LIGHTHOUSE_1F, 5 warp_event 16, 11, OLIVINE_LIGHTHOUSE_3F, 4 warp_event 17, 11, OLIVINE_LIGHTHOUSE_3F, 5 db 0 ; coord events db 0 ; bg events db 2 ; object events object_event 9, 3, SPRITE_SAILOR, SPRITEMOVEDATA_STANDING_RIGHT, 0, 0, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_TRAINER, 3, TrainerSailorHuey, -1 object_event 17, 8, SPRITE_GENTLEMAN, SPRITEMOVEDATA_STANDING_LEFT, 0, 0, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_TRAINER, 3, TrainerGentlemanAlfred, -1
; A021039: Decimal expansion of 1/35. ; 0,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8 mov $2,1 mov $3,2 lpb $3 sub $3,1 add $0,$3 sub $0,1 mov $1,$2 lpb $0 sub $0,1 lpb $2 mod $2,7 lpe mul $2,3 lpe lpe sub $1,1 mod $1,10 mov $0,$1
; A025699: Index of 3^n within sequence of numbers of form 3^i*8^j. ; 1,2,4,6,9,12,16,20,25,30,36,42,49,56,64,72,81,90,100,111,122,134,146,159,172,186,200,215,230,246,262,279,296,314,332,351,371,391,412,433,455,477,500,523,547,571,596,621,647,673,700,727,755,784,813,843,873,904,935 mov $3,$0 add $3,1 mov $6,$0 lpb $3 mov $0,$6 sub $3,1 sub $0,$3 mov $8,$0 add $8,1 mov $11,$0 mov $12,0 lpb $8 mov $0,$11 sub $8,1 sub $0,$8 mov $2,$0 mov $0,69 sub $2,2 mod $2,17 mov $7,1 mov $10,$2 add $10,1 sub $0,$10 mov $9,0 mov $10,2 lpb $0 sub $0,1 gcd $0,2 add $9,$7 mul $0,$9 mov $5,$10 add $5,2 lpe mov $2,0 sub $5,$0 add $2,$5 mov $4,$2 sub $4,2 add $12,$4 lpe add $1,$12 lpe mov $0,$1
#include <iostream> using namespace std; int fak(int n) { if (n <= 1) return 1; // exit else return n * fak(n - 1); } int main() { cout << "5!=" << fak(5) << endl; return 0; }
; A083679: Decimal expansion of log(4/3). ; Submitted by Jon Maiga ; 2,8,7,6,8,2,0,7,2,4,5,1,7,8,0,9,2,7,4,3,9,2,1,9,0,0,5,9,9,3,8,2,7,4,3,1,5,0,3,5,0,9,7,1,0,8,9,7,7,6,1,0,5,6,5,0,6,6,6,5,6,8,5,3,4,9,2,9,2,9,5,0,7,2,0,7,8,0,4,6,4,3,3,8,1,1,0,8,9,9,1,7,9,1,0,5,2,8,6,2 add $0,1 mov $2,1 mov $3,$0 mul $3,5 lpb $3 mul $1,$3 mov $5,$3 mul $5,4 add $5,4 mul $2,$5 add $1,$2 div $1,$0 div $2,$0 sub $3,1 lpe div $1,4 mov $4,10 pow $4,$0 div $2,$4 div $1,$2 mov $0,$1 mod $0,10
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign // Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign // Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory // Mark Dewing, markdewing@gmail.com, University of Illinois at Urbana-Champaign // // File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign ////////////////////////////////////////////////////////////////////////////////////// /** @file PWParameterSet.cpp * @brief Utility class to handle hdf5 */ #include "PWParameterSet.h" #include "Message/Communicate.h" #include "Message/CommOperators.h" namespace qmcplusplus { PWParameterSet::PWParameterSet(Communicate* comm) : MPIObjectBase(comm), hasSpin(true), twistIndex(0), numBands(0), Ecut(-1), Rcut(-1), BufferRadius(-1), BoxDup(1), paramTag("parameters"), basisTag("basis"), pwTag("planewaves"), pwMultTag("multipliers"), eigTag("eigenstates"), twistTag("twist"), bandTag("band"), spinTag("spin"), eigvecTag("eigenvector") { m_param.setName("h5tag"); m_param.add(twistIndex, "twistIndex", "int"); m_param.add(Rcut, "rcut", "double"); m_param.add(BufferRadius, "bufferLayer", "double"); m_param.add(BoxDup, "expand", "int3"); m_param.add(paramTag, "parameters", "string"); m_param.add(basisTag, "basis", "string"); m_param.add(pwTag, "planewaves", "string"); m_param.add(pwMultTag, "multiplers", "string"); m_param.add(eigTag, "eigenstates", "string"); m_param.add(twistTag, "twist", "string"); m_param.add(bandTag, "band", "string"); m_param.add(spinTag, "spin", "string"); m_param.add(eigvecTag, "eigenvector", "string"); } double PWParameterSet::getEcut(double ecut) { if (Ecut < 0 || Ecut >= ecut) Ecut = ecut; return Ecut; } bool PWParameterSet::getEigVectorType(hid_t h) { int rank = 0; if (is_manager()) { std::ostringstream oss; oss << "/" << eigTag << "/" << twistTag << twistIndex << "/" << bandTag << 0; //if(version[1]==10) if (hasSpin) oss << "/" << spinTag << 0; oss << "/eigenvector"; hsize_t dimTot[4]; hid_t dataset = H5Dopen(h, oss.str().c_str()); hid_t dataspace = H5Dget_space(dataset); rank = H5Sget_simple_extent_ndims(dataspace); int status_n = H5Sget_simple_extent_dims(dataspace, dimTot, NULL); } myComm->bcast(rank); return rank == 4; } bool PWParameterSet::hasComplexData(hid_t h_file) { int iscomplex = 0; // Should be the tag "/electrons/psi_r_is_complex", but the test HDF files // don't have this set #if 0 if(is_manager()) { std::ostringstream oss; oss << paramTag << "/complex_coefficients"; HDFAttribIO<int> creader(iscomplex); creader.read(h_file,oss.str().c_str()); } #endif myComm->bcast(iscomplex); return iscomplex; } std::string PWParameterSet::getTwistAngleName() { std::ostringstream oss; oss << eigTag << "/" << twistTag << twistIndex << "/twist_angle"; return oss.str(); } std::string PWParameterSet::getTwistName() { return getTwistName(twistIndex); } std::string PWParameterSet::getTwistName(int i) { std::ostringstream oss; oss << twistTag << i; return oss.str(); } std::string PWParameterSet::getBandName(int ib, int ispin) { std::ostringstream oss; oss << "spin_" << ispin << "/" << "state_" << ib; return oss.str(); } std::string PWParameterSet::getEigVectorName(const std::string& hg, int ib, int ispin) { std::ostringstream oss; oss << hg << "/" << bandTag << ib; //if(version[1]==10) if (hasSpin) { oss << "/" << spinTag << ispin; } oss << "/eigenvector"; return oss.str(); } std::string PWParameterSet::getCenterName(const std::string& hg, int ib) { std::ostringstream oss; oss << hg << "/" << bandTag << ib << "/center"; return oss.str(); } std::string PWParameterSet::getOriginName(const std::string& hg, int ib) { std::ostringstream oss; oss << hg << "/" << bandTag << ib << "/origin"; return oss.str(); } std::string PWParameterSet::getEigVectorName(int ib, int ispin) { std::ostringstream oss; oss << "/" << eigTag << "/" << twistTag << twistIndex << "/" << bandTag << ib; //if(version[1]==10) if (hasSpin) { oss << "/" << spinTag << ispin; } oss << "/eigenvector"; return oss.str(); } std::string PWParameterSet::getBandName(int ib) { std::ostringstream oss; oss << bandTag << ib; return oss.str(); } std::string PWParameterSet::getSpinName(int ispin) { std::ostringstream oss; oss << spinTag << ispin; return oss.str(); } void PWParameterSet::checkVersion(hid_t h) { if (is_manager()) { hid_t dataset = H5Dopen(h, "version"); hid_t datatype = H5Dget_type(dataset); H5T_class_t classtype = H5Tget_class(datatype); H5Tclose(datatype); H5Dclose(dataset); if (classtype == H5T_INTEGER) { HDFAttribIO<TinyVector<int, 2>> hdfver(version); hdfver.read(h, "version"); } else if (classtype == H5T_FLOAT) { TinyVector<double, 2> vt; HDFAttribIO<TinyVector<double, 2>> hdfver(vt); hdfver.read(h, "version"); version[0] = int(vt[0]); version[1] = int(vt[1]); } //else //{ // APP_ABORT("PWParameterSet::checkVersion The type of version is not integer or double."); //} } myComm->bcast(version); app_log() << "\tWavefunction HDF version: " << version[0] << "." << version[1] << std::endl; if (version[0] == 0) { if (version[1] == 11) { hasSpin = false; paramTag = "parameters_0"; basisTag = "basis_1"; pwTag = "planewaves"; pwMultTag = "multipliers"; eigTag = "eigenstates_3"; twistTag = "twist_"; bandTag = "band_"; } else if (version[1] == 10) { pwMultTag = "planewaves"; pwTag = "0"; } } } void PWParameterSet::writeParameters(hid_t gid) { #if defined(QMC_COMPLEX) int iscomplex = 1; #else int iscomplex = 0; #endif hid_t h1 = H5Gcreate(gid, "parameters", 0); HDFAttribIO<int> i1(iscomplex); i1.write(h1, "complex_coefficients"); TinyVector<int, 2> v1(0, 10); HDFAttribIO<TinyVector<int, 2>> i2(v1); i2.write(gid, "version"); H5Gclose(h1); } } // namespace qmcplusplus
; ; Copyright (c) 2010 The WebM project authors. All Rights Reserved. ; ; Use of this source code is governed by a BSD-style license ; that can be found in the LICENSE file in the root of the source ; tree. An additional intellectual property rights grant can be found ; in the file PATENTS. All contributing project authors may ; be found in the AUTHORS file in the root of the source tree. ; %include "vpx_ports/x86_abi_support.asm" %macro STACK_FRAME_CREATE_X3 0 %if ABI_IS_32BIT %define src_ptr rsi %define src_stride rax %define ref_ptr rdi %define ref_stride rdx %define end_ptr rcx %define ret_var rbx %define result_ptr arg(4) %define max_err arg(4) %define height dword ptr arg(4) push rbp mov rbp, rsp push rsi push rdi push rbx mov rsi, arg(0) ; src_ptr mov rdi, arg(2) ; ref_ptr movsxd rax, dword ptr arg(1) ; src_stride movsxd rdx, dword ptr arg(3) ; ref_stride %else %ifidn __OUTPUT_FORMAT__,x64 SAVE_XMM 7, u %define src_ptr rcx %define src_stride rdx %define ref_ptr r8 %define ref_stride r9 %define end_ptr r10 %define ret_var r11 %define result_ptr [rsp+xmm_stack_space+8+4*8] %define max_err [rsp+xmm_stack_space+8+4*8] %define height dword ptr [rsp+xmm_stack_space+8+4*8] %else %define src_ptr rdi %define src_stride rsi %define ref_ptr rdx %define ref_stride rcx %define end_ptr r9 %define ret_var r10 %define result_ptr r8 %define max_err r8 %define height r8 %endif %endif %endmacro %macro STACK_FRAME_DESTROY_X3 0 %define src_ptr %define src_stride %define ref_ptr %define ref_stride %define end_ptr %define ret_var %define result_ptr %define max_err %define height %if ABI_IS_32BIT pop rbx pop rdi pop rsi pop rbp %else %ifidn __OUTPUT_FORMAT__,x64 RESTORE_XMM %endif %endif ret %endmacro %macro STACK_FRAME_CREATE_X4 0 %if ABI_IS_32BIT %define src_ptr rsi %define src_stride rax %define r0_ptr rcx %define r1_ptr rdx %define r2_ptr rbx %define r3_ptr rdi %define ref_stride rbp %define result_ptr arg(4) push rbp mov rbp, rsp push rsi push rdi push rbx push rbp mov rdi, arg(2) ; ref_ptr_base LOAD_X4_ADDRESSES rdi, rcx, rdx, rax, rdi mov rsi, arg(0) ; src_ptr movsxd rbx, dword ptr arg(1) ; src_stride movsxd rbp, dword ptr arg(3) ; ref_stride xchg rbx, rax %else %ifidn __OUTPUT_FORMAT__,x64 SAVE_XMM 7, u %define src_ptr rcx %define src_stride rdx %define r0_ptr rsi %define r1_ptr r10 %define r2_ptr r11 %define r3_ptr r8 %define ref_stride r9 %define result_ptr [rsp+xmm_stack_space+16+4*8] push rsi LOAD_X4_ADDRESSES r8, r0_ptr, r1_ptr, r2_ptr, r3_ptr %else %define src_ptr rdi %define src_stride rsi %define r0_ptr r9 %define r1_ptr r10 %define r2_ptr r11 %define r3_ptr rdx %define ref_stride rcx %define result_ptr r8 LOAD_X4_ADDRESSES rdx, r0_ptr, r1_ptr, r2_ptr, r3_ptr %endif %endif %endmacro %macro STACK_FRAME_DESTROY_X4 0 %define src_ptr %define src_stride %define r0_ptr %define r1_ptr %define r2_ptr %define r3_ptr %define ref_stride %define result_ptr %if ABI_IS_32BIT pop rbx pop rdi pop rsi pop rbp %else %ifidn __OUTPUT_FORMAT__,x64 pop rsi RESTORE_XMM %endif %endif ret %endmacro %macro PROCESS_16X2X3 5 %if %1==0 movdqa xmm0, XMMWORD PTR [%2] lddqu xmm5, XMMWORD PTR [%3] lddqu xmm6, XMMWORD PTR [%3+1] lddqu xmm7, XMMWORD PTR [%3+2] psadbw xmm5, xmm0 psadbw xmm6, xmm0 psadbw xmm7, xmm0 %else movdqa xmm0, XMMWORD PTR [%2] lddqu xmm1, XMMWORD PTR [%3] lddqu xmm2, XMMWORD PTR [%3+1] lddqu xmm3, XMMWORD PTR [%3+2] psadbw xmm1, xmm0 psadbw xmm2, xmm0 psadbw xmm3, xmm0 paddw xmm5, xmm1 paddw xmm6, xmm2 paddw xmm7, xmm3 %endif movdqa xmm0, XMMWORD PTR [%2+%4] lddqu xmm1, XMMWORD PTR [%3+%5] lddqu xmm2, XMMWORD PTR [%3+%5+1] lddqu xmm3, XMMWORD PTR [%3+%5+2] %if %1==0 || %1==1 lea %2, [%2+%4*2] lea %3, [%3+%5*2] %endif psadbw xmm1, xmm0 psadbw xmm2, xmm0 psadbw xmm3, xmm0 paddw xmm5, xmm1 paddw xmm6, xmm2 paddw xmm7, xmm3 %endmacro %macro PROCESS_8X2X3 5 %if %1==0 movq mm0, QWORD PTR [%2] movq mm5, QWORD PTR [%3] movq mm6, QWORD PTR [%3+1] movq mm7, QWORD PTR [%3+2] psadbw mm5, mm0 psadbw mm6, mm0 psadbw mm7, mm0 %else movq mm0, QWORD PTR [%2] movq mm1, QWORD PTR [%3] movq mm2, QWORD PTR [%3+1] movq mm3, QWORD PTR [%3+2] psadbw mm1, mm0 psadbw mm2, mm0 psadbw mm3, mm0 paddw mm5, mm1 paddw mm6, mm2 paddw mm7, mm3 %endif movq mm0, QWORD PTR [%2+%4] movq mm1, QWORD PTR [%3+%5] movq mm2, QWORD PTR [%3+%5+1] movq mm3, QWORD PTR [%3+%5+2] %if %1==0 || %1==1 lea %2, [%2+%4*2] lea %3, [%3+%5*2] %endif psadbw mm1, mm0 psadbw mm2, mm0 psadbw mm3, mm0 paddw mm5, mm1 paddw mm6, mm2 paddw mm7, mm3 %endmacro %macro LOAD_X4_ADDRESSES 5 mov %2, [%1+REG_SZ_BYTES*0] mov %3, [%1+REG_SZ_BYTES*1] mov %4, [%1+REG_SZ_BYTES*2] mov %5, [%1+REG_SZ_BYTES*3] %endmacro %macro PROCESS_16X2X4 8 %if %1==0 movdqa xmm0, XMMWORD PTR [%2] lddqu xmm4, XMMWORD PTR [%3] lddqu xmm5, XMMWORD PTR [%4] lddqu xmm6, XMMWORD PTR [%5] lddqu xmm7, XMMWORD PTR [%6] psadbw xmm4, xmm0 psadbw xmm5, xmm0 psadbw xmm6, xmm0 psadbw xmm7, xmm0 %else movdqa xmm0, XMMWORD PTR [%2] lddqu xmm1, XMMWORD PTR [%3] lddqu xmm2, XMMWORD PTR [%4] lddqu xmm3, XMMWORD PTR [%5] psadbw xmm1, xmm0 psadbw xmm2, xmm0 psadbw xmm3, xmm0 paddw xmm4, xmm1 lddqu xmm1, XMMWORD PTR [%6] paddw xmm5, xmm2 paddw xmm6, xmm3 psadbw xmm1, xmm0 paddw xmm7, xmm1 %endif movdqa xmm0, XMMWORD PTR [%2+%7] lddqu xmm1, XMMWORD PTR [%3+%8] lddqu xmm2, XMMWORD PTR [%4+%8] lddqu xmm3, XMMWORD PTR [%5+%8] psadbw xmm1, xmm0 psadbw xmm2, xmm0 psadbw xmm3, xmm0 paddw xmm4, xmm1 lddqu xmm1, XMMWORD PTR [%6+%8] paddw xmm5, xmm2 paddw xmm6, xmm3 %if %1==0 || %1==1 lea %2, [%2+%7*2] lea %3, [%3+%8*2] lea %4, [%4+%8*2] lea %5, [%5+%8*2] lea %6, [%6+%8*2] %endif psadbw xmm1, xmm0 paddw xmm7, xmm1 %endmacro %macro PROCESS_8X2X4 8 %if %1==0 movq mm0, QWORD PTR [%2] movq mm4, QWORD PTR [%3] movq mm5, QWORD PTR [%4] movq mm6, QWORD PTR [%5] movq mm7, QWORD PTR [%6] psadbw mm4, mm0 psadbw mm5, mm0 psadbw mm6, mm0 psadbw mm7, mm0 %else movq mm0, QWORD PTR [%2] movq mm1, QWORD PTR [%3] movq mm2, QWORD PTR [%4] movq mm3, QWORD PTR [%5] psadbw mm1, mm0 psadbw mm2, mm0 psadbw mm3, mm0 paddw mm4, mm1 movq mm1, QWORD PTR [%6] paddw mm5, mm2 paddw mm6, mm3 psadbw mm1, mm0 paddw mm7, mm1 %endif movq mm0, QWORD PTR [%2+%7] movq mm1, QWORD PTR [%3+%8] movq mm2, QWORD PTR [%4+%8] movq mm3, QWORD PTR [%5+%8] psadbw mm1, mm0 psadbw mm2, mm0 psadbw mm3, mm0 paddw mm4, mm1 movq mm1, QWORD PTR [%6+%8] paddw mm5, mm2 paddw mm6, mm3 %if %1==0 || %1==1 lea %2, [%2+%7*2] lea %3, [%3+%8*2] lea %4, [%4+%8*2] lea %5, [%5+%8*2] lea %6, [%6+%8*2] %endif psadbw mm1, mm0 paddw mm7, mm1 %endmacro ;void int vp8_sad16x16x3_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr, ; int ref_stride, ; int *results) global sym(vp8_sad16x16x3_sse3) sym(vp8_sad16x16x3_sse3): STACK_FRAME_CREATE_X3 PROCESS_16X2X3 0, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_16X2X3 2, src_ptr, ref_ptr, src_stride, ref_stride mov rcx, result_ptr movq xmm0, xmm5 psrldq xmm5, 8 paddw xmm0, xmm5 movd [rcx], xmm0 ;- movq xmm0, xmm6 psrldq xmm6, 8 paddw xmm0, xmm6 movd [rcx+4], xmm0 ;- movq xmm0, xmm7 psrldq xmm7, 8 paddw xmm0, xmm7 movd [rcx+8], xmm0 STACK_FRAME_DESTROY_X3 ;void int vp8_sad16x8x3_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr, ; int ref_stride, ; int *results) global sym(vp8_sad16x8x3_sse3) sym(vp8_sad16x8x3_sse3): STACK_FRAME_CREATE_X3 PROCESS_16X2X3 0, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_16X2X3 2, src_ptr, ref_ptr, src_stride, ref_stride mov rcx, result_ptr movq xmm0, xmm5 psrldq xmm5, 8 paddw xmm0, xmm5 movd [rcx], xmm0 ;- movq xmm0, xmm6 psrldq xmm6, 8 paddw xmm0, xmm6 movd [rcx+4], xmm0 ;- movq xmm0, xmm7 psrldq xmm7, 8 paddw xmm0, xmm7 movd [rcx+8], xmm0 STACK_FRAME_DESTROY_X3 ;void int vp8_sad8x16x3_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr, ; int ref_stride, ; int *results) global sym(vp8_sad8x16x3_sse3) sym(vp8_sad8x16x3_sse3): STACK_FRAME_CREATE_X3 PROCESS_8X2X3 0, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_8X2X3 2, src_ptr, ref_ptr, src_stride, ref_stride mov rcx, result_ptr punpckldq mm5, mm6 movq [rcx], mm5 movd [rcx+8], mm7 STACK_FRAME_DESTROY_X3 ;void int vp8_sad8x8x3_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr, ; int ref_stride, ; int *results) global sym(vp8_sad8x8x3_sse3) sym(vp8_sad8x8x3_sse3): STACK_FRAME_CREATE_X3 PROCESS_8X2X3 0, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride PROCESS_8X2X3 2, src_ptr, ref_ptr, src_stride, ref_stride mov rcx, result_ptr punpckldq mm5, mm6 movq [rcx], mm5 movd [rcx+8], mm7 STACK_FRAME_DESTROY_X3 ;void int vp8_sad4x4x3_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr, ; int ref_stride, ; int *results) global sym(vp8_sad4x4x3_sse3) sym(vp8_sad4x4x3_sse3): STACK_FRAME_CREATE_X3 movd mm0, DWORD PTR [src_ptr] movd mm1, DWORD PTR [ref_ptr] movd mm2, DWORD PTR [src_ptr+src_stride] movd mm3, DWORD PTR [ref_ptr+ref_stride] punpcklbw mm0, mm2 punpcklbw mm1, mm3 movd mm4, DWORD PTR [ref_ptr+1] movd mm5, DWORD PTR [ref_ptr+2] movd mm2, DWORD PTR [ref_ptr+ref_stride+1] movd mm3, DWORD PTR [ref_ptr+ref_stride+2] psadbw mm1, mm0 punpcklbw mm4, mm2 punpcklbw mm5, mm3 psadbw mm4, mm0 psadbw mm5, mm0 lea src_ptr, [src_ptr+src_stride*2] lea ref_ptr, [ref_ptr+ref_stride*2] movd mm0, DWORD PTR [src_ptr] movd mm2, DWORD PTR [ref_ptr] movd mm3, DWORD PTR [src_ptr+src_stride] movd mm6, DWORD PTR [ref_ptr+ref_stride] punpcklbw mm0, mm3 punpcklbw mm2, mm6 movd mm3, DWORD PTR [ref_ptr+1] movd mm7, DWORD PTR [ref_ptr+2] psadbw mm2, mm0 paddw mm1, mm2 movd mm2, DWORD PTR [ref_ptr+ref_stride+1] movd mm6, DWORD PTR [ref_ptr+ref_stride+2] punpcklbw mm3, mm2 punpcklbw mm7, mm6 psadbw mm3, mm0 psadbw mm7, mm0 paddw mm3, mm4 paddw mm7, mm5 mov rcx, result_ptr punpckldq mm1, mm3 movq [rcx], mm1 movd [rcx+8], mm7 STACK_FRAME_DESTROY_X3 ;unsigned int vp8_sad16x16_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr, ; int ref_stride, ; int max_err) ;%define lddqu movdqu global sym(vp8_sad16x16_sse3) sym(vp8_sad16x16_sse3): STACK_FRAME_CREATE_X3 mov end_ptr, 4 pxor xmm7, xmm7 .vp8_sad16x16_sse3_loop: movdqa xmm0, XMMWORD PTR [src_ptr] movdqu xmm1, XMMWORD PTR [ref_ptr] movdqa xmm2, XMMWORD PTR [src_ptr+src_stride] movdqu xmm3, XMMWORD PTR [ref_ptr+ref_stride] lea src_ptr, [src_ptr+src_stride*2] lea ref_ptr, [ref_ptr+ref_stride*2] movdqa xmm4, XMMWORD PTR [src_ptr] movdqu xmm5, XMMWORD PTR [ref_ptr] movdqa xmm6, XMMWORD PTR [src_ptr+src_stride] psadbw xmm0, xmm1 movdqu xmm1, XMMWORD PTR [ref_ptr+ref_stride] psadbw xmm2, xmm3 psadbw xmm4, xmm5 psadbw xmm6, xmm1 lea src_ptr, [src_ptr+src_stride*2] lea ref_ptr, [ref_ptr+ref_stride*2] paddw xmm7, xmm0 paddw xmm7, xmm2 paddw xmm7, xmm4 paddw xmm7, xmm6 sub end_ptr, 1 jne .vp8_sad16x16_sse3_loop movq xmm0, xmm7 psrldq xmm7, 8 paddw xmm0, xmm7 movq rax, xmm0 STACK_FRAME_DESTROY_X3 ;void vp8_copy32xn_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *dst_ptr, ; int dst_stride, ; int height); global sym(vp8_copy32xn_sse3) sym(vp8_copy32xn_sse3): STACK_FRAME_CREATE_X3 .block_copy_sse3_loopx4: lea end_ptr, [src_ptr+src_stride*2] movdqu xmm0, XMMWORD PTR [src_ptr] movdqu xmm1, XMMWORD PTR [src_ptr + 16] movdqu xmm2, XMMWORD PTR [src_ptr + src_stride] movdqu xmm3, XMMWORD PTR [src_ptr + src_stride + 16] movdqu xmm4, XMMWORD PTR [end_ptr] movdqu xmm5, XMMWORD PTR [end_ptr + 16] movdqu xmm6, XMMWORD PTR [end_ptr + src_stride] movdqu xmm7, XMMWORD PTR [end_ptr + src_stride + 16] lea src_ptr, [src_ptr+src_stride*4] lea end_ptr, [ref_ptr+ref_stride*2] movdqa XMMWORD PTR [ref_ptr], xmm0 movdqa XMMWORD PTR [ref_ptr + 16], xmm1 movdqa XMMWORD PTR [ref_ptr + ref_stride], xmm2 movdqa XMMWORD PTR [ref_ptr + ref_stride + 16], xmm3 movdqa XMMWORD PTR [end_ptr], xmm4 movdqa XMMWORD PTR [end_ptr + 16], xmm5 movdqa XMMWORD PTR [end_ptr + ref_stride], xmm6 movdqa XMMWORD PTR [end_ptr + ref_stride + 16], xmm7 lea ref_ptr, [ref_ptr+ref_stride*4] sub height, 4 cmp height, 4 jge .block_copy_sse3_loopx4 ;Check to see if there is more rows need to be copied. cmp height, 0 je .copy_is_done .block_copy_sse3_loop: movdqu xmm0, XMMWORD PTR [src_ptr] movdqu xmm1, XMMWORD PTR [src_ptr + 16] lea src_ptr, [src_ptr+src_stride] movdqa XMMWORD PTR [ref_ptr], xmm0 movdqa XMMWORD PTR [ref_ptr + 16], xmm1 lea ref_ptr, [ref_ptr+ref_stride] sub height, 1 jne .block_copy_sse3_loop .copy_is_done: STACK_FRAME_DESTROY_X3 ;void vp8_sad16x16x4d_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr_base, ; int ref_stride, ; int *results) global sym(vp8_sad16x16x4d_sse3) sym(vp8_sad16x16x4d_sse3): STACK_FRAME_CREATE_X4 PROCESS_16X2X4 0, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_16X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_16X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_16X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_16X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_16X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_16X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_16X2X4 2, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride %if ABI_IS_32BIT pop rbp %endif mov rcx, result_ptr movq xmm0, xmm4 psrldq xmm4, 8 paddw xmm0, xmm4 movd [rcx], xmm0 ;- movq xmm0, xmm5 psrldq xmm5, 8 paddw xmm0, xmm5 movd [rcx+4], xmm0 ;- movq xmm0, xmm6 psrldq xmm6, 8 paddw xmm0, xmm6 movd [rcx+8], xmm0 ;- movq xmm0, xmm7 psrldq xmm7, 8 paddw xmm0, xmm7 movd [rcx+12], xmm0 STACK_FRAME_DESTROY_X4 ;void vp8_sad16x8x4d_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr_base, ; int ref_stride, ; int *results) global sym(vp8_sad16x8x4d_sse3) sym(vp8_sad16x8x4d_sse3): STACK_FRAME_CREATE_X4 PROCESS_16X2X4 0, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_16X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_16X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_16X2X4 2, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride %if ABI_IS_32BIT pop rbp %endif mov rcx, result_ptr movq xmm0, xmm4 psrldq xmm4, 8 paddw xmm0, xmm4 movd [rcx], xmm0 ;- movq xmm0, xmm5 psrldq xmm5, 8 paddw xmm0, xmm5 movd [rcx+4], xmm0 ;- movq xmm0, xmm6 psrldq xmm6, 8 paddw xmm0, xmm6 movd [rcx+8], xmm0 ;- movq xmm0, xmm7 psrldq xmm7, 8 paddw xmm0, xmm7 movd [rcx+12], xmm0 STACK_FRAME_DESTROY_X4 ;void int vp8_sad8x16x4d_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr, ; int ref_stride, ; int *results) global sym(vp8_sad8x16x4d_sse3) sym(vp8_sad8x16x4d_sse3): STACK_FRAME_CREATE_X4 PROCESS_8X2X4 0, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_8X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_8X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_8X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_8X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_8X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_8X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_8X2X4 2, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride %if ABI_IS_32BIT pop rbp %endif mov rcx, result_ptr punpckldq mm4, mm5 punpckldq mm6, mm7 movq [rcx], mm4 movq [rcx+8], mm6 STACK_FRAME_DESTROY_X4 ;void int vp8_sad8x8x4d_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr, ; int ref_stride, ; int *results) global sym(vp8_sad8x8x4d_sse3) sym(vp8_sad8x8x4d_sse3): STACK_FRAME_CREATE_X4 PROCESS_8X2X4 0, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_8X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_8X2X4 1, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride PROCESS_8X2X4 2, src_ptr, r0_ptr, r1_ptr, r2_ptr, r3_ptr, src_stride, ref_stride %if ABI_IS_32BIT pop rbp %endif mov rcx, result_ptr punpckldq mm4, mm5 punpckldq mm6, mm7 movq [rcx], mm4 movq [rcx+8], mm6 STACK_FRAME_DESTROY_X4 ;void int vp8_sad4x4x4d_sse3( ; unsigned char *src_ptr, ; int src_stride, ; unsigned char *ref_ptr, ; int ref_stride, ; int *results) global sym(vp8_sad4x4x4d_sse3) sym(vp8_sad4x4x4d_sse3): STACK_FRAME_CREATE_X4 movd mm0, DWORD PTR [src_ptr] movd mm1, DWORD PTR [r0_ptr] movd mm2, DWORD PTR [src_ptr+src_stride] movd mm3, DWORD PTR [r0_ptr+ref_stride] punpcklbw mm0, mm2 punpcklbw mm1, mm3 movd mm4, DWORD PTR [r1_ptr] movd mm5, DWORD PTR [r2_ptr] movd mm6, DWORD PTR [r3_ptr] movd mm2, DWORD PTR [r1_ptr+ref_stride] movd mm3, DWORD PTR [r2_ptr+ref_stride] movd mm7, DWORD PTR [r3_ptr+ref_stride] psadbw mm1, mm0 punpcklbw mm4, mm2 punpcklbw mm5, mm3 punpcklbw mm6, mm7 psadbw mm4, mm0 psadbw mm5, mm0 psadbw mm6, mm0 lea src_ptr, [src_ptr+src_stride*2] lea r0_ptr, [r0_ptr+ref_stride*2] lea r1_ptr, [r1_ptr+ref_stride*2] lea r2_ptr, [r2_ptr+ref_stride*2] lea r3_ptr, [r3_ptr+ref_stride*2] movd mm0, DWORD PTR [src_ptr] movd mm2, DWORD PTR [r0_ptr] movd mm3, DWORD PTR [src_ptr+src_stride] movd mm7, DWORD PTR [r0_ptr+ref_stride] punpcklbw mm0, mm3 punpcklbw mm2, mm7 movd mm3, DWORD PTR [r1_ptr] movd mm7, DWORD PTR [r2_ptr] psadbw mm2, mm0 %if ABI_IS_32BIT mov rax, rbp pop rbp %define ref_stride rax %endif mov rsi, result_ptr paddw mm1, mm2 movd [rsi], mm1 movd mm2, DWORD PTR [r1_ptr+ref_stride] movd mm1, DWORD PTR [r2_ptr+ref_stride] punpcklbw mm3, mm2 punpcklbw mm7, mm1 psadbw mm3, mm0 psadbw mm7, mm0 movd mm2, DWORD PTR [r3_ptr] movd mm1, DWORD PTR [r3_ptr+ref_stride] paddw mm3, mm4 paddw mm7, mm5 movd [rsi+4], mm3 punpcklbw mm2, mm1 movd [rsi+8], mm7 psadbw mm2, mm0 paddw mm2, mm6 movd [rsi+12], mm2 STACK_FRAME_DESTROY_X4
// © 2017 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include <cstdlib> #include "unicode/simpleformatter.h" #include "unicode/ures.h" #include "ureslocs.h" #include "charstr.h" #include "uresimp.h" #include "measunit_impl.h" #include "number_longnames.h" #include "number_microprops.h" #include <algorithm> #include "cstring.h" #include "util.h" using namespace icu; using namespace icu::number; using namespace icu::number::impl; namespace { /** * Display Name (this format has no placeholder). * * Used as an index into the LongNameHandler::simpleFormats array. Units * resources cover the normal set of PluralRules keys, as well as `dnam` and * `per` forms. */ constexpr int32_t DNAM_INDEX = StandardPlural::Form::COUNT; /** * "per" form (e.g. "{0} per day" is day's "per" form). * * Used as an index into the LongNameHandler::simpleFormats array. Units * resources cover the normal set of PluralRules keys, as well as `dnam` and * `per` forms. */ constexpr int32_t PER_INDEX = StandardPlural::Form::COUNT + 1; /** * Gender of the word, in languages with grammatical gender. */ constexpr int32_t GENDER_INDEX = StandardPlural::Form::COUNT + 2; // Number of keys in the array populated by PluralTableSink. constexpr int32_t ARRAY_LENGTH = StandardPlural::Form::COUNT + 3; // TODO(icu-units#28): load this list from resources, after creating a "&set" // function for use in ldml2icu rules. const int32_t GENDER_COUNT = 7; const char *gGenders[GENDER_COUNT] = {"animate", "common", "feminine", "inanimate", "masculine", "neuter", "personal"}; // Converts a UnicodeString to a const char*, either pointing to a string in // gGenders, or pointing to an empty string if an appropriate string was not // found. const char *getGenderString(UnicodeString uGender, UErrorCode status) { if (uGender.length() == 0) { return ""; } CharString gender; gender.appendInvariantChars(uGender, status); if (U_FAILURE(status)) { return ""; } int32_t first = 0; int32_t last = GENDER_COUNT; while (first < last) { int32_t mid = (first + last) / 2; int32_t cmp = uprv_strcmp(gender.data(), gGenders[mid]); if (cmp == 0) { return gGenders[mid]; } else if (cmp > 0) { first = mid + 1; } else if (cmp < 0) { last = mid; } } // We don't return an error in case our gGenders list is incomplete in // production. // // TODO(icu-units#28): a unit test checking all locales' genders are covered // by gGenders? Else load a complete list of genders found in // grammaticalFeatures in an initOnce. return ""; } // Returns the array index that corresponds to the given pluralKeyword. static int32_t getIndex(const char* pluralKeyword, UErrorCode& status) { // pluralKeyword can also be "dnam", "per", or "gender" switch (*pluralKeyword) { case 'd': if (uprv_strcmp(pluralKeyword + 1, "nam") == 0) { return DNAM_INDEX; } break; case 'g': if (uprv_strcmp(pluralKeyword + 1, "ender") == 0) { return GENDER_INDEX; } break; case 'p': if (uprv_strcmp(pluralKeyword + 1, "er") == 0) { return PER_INDEX; } break; default: break; } StandardPlural::Form plural = StandardPlural::fromString(pluralKeyword, status); return plural; } // Selects a string out of the `strings` array which corresponds to the // specified plural form, with fallback to the OTHER form. // // The `strings` array must have ARRAY_LENGTH items: one corresponding to each // of the plural forms, plus a display name ("dnam") and a "per" form. static UnicodeString getWithPlural( const UnicodeString* strings, StandardPlural::Form plural, UErrorCode& status) { UnicodeString result = strings[plural]; if (result.isBogus()) { result = strings[StandardPlural::Form::OTHER]; } if (result.isBogus()) { // There should always be data in the "other" plural variant. status = U_INTERNAL_PROGRAM_ERROR; } return result; } enum PlaceholderPosition { PH_EMPTY, PH_NONE, PH_BEGINNING, PH_MIDDLE, PH_END }; /** * Returns three outputs extracted from pattern. * * @param coreUnit is extracted as per Extract(...) in the spec: * https://unicode.org/reports/tr35/tr35-general.html#compound-units * @param PlaceholderPosition indicates where in the string the placeholder was * found. * @param joinerChar Iff the placeholder was at the beginning or end, joinerChar * contains the space character (if any) that separated the placeholder from * the rest of the pattern. Otherwise, joinerChar is set to NUL. Only one * space character is considered. */ void extractCorePattern(const UnicodeString &pattern, UnicodeString &coreUnit, PlaceholderPosition &placeholderPosition, UChar &joinerChar) { joinerChar = 0; int32_t len = pattern.length(); if (pattern.startsWith(u"{0}", 3)) { placeholderPosition = PH_BEGINNING; if (u_isJavaSpaceChar(pattern[3])) { joinerChar = pattern[3]; coreUnit.setTo(pattern, 4, len - 4); } else { coreUnit.setTo(pattern, 3, len - 3); } } else if (pattern.endsWith(u"{0}", 3)) { placeholderPosition = PH_END; if (u_isJavaSpaceChar(pattern[len - 4])) { coreUnit.setTo(pattern, 0, len - 4); joinerChar = pattern[len - 4]; } else { coreUnit.setTo(pattern, 0, len - 3); } } else if (pattern.indexOf(u"{0}", 3, 1, len - 2) == -1) { placeholderPosition = PH_NONE; coreUnit = pattern; } else { placeholderPosition = PH_MIDDLE; coreUnit = pattern; } } ////////////////////////// /// BEGIN DATA LOADING /// ////////////////////////// // Gets the gender of a built-in unit: unit must be a built-in. Returns an empty // string both in case of unknown gender and in case of unknown unit. UnicodeString getGenderForBuiltin(const Locale &locale, const MeasureUnit &builtinUnit, UErrorCode &status) { LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, locale.getName(), &status)); if (U_FAILURE(status)) { return {}; } // Map duration-year-person, duration-week-person, etc. to duration-year, duration-week, ... // TODO(ICU-20400): Get duration-*-person data properly with aliases. StringPiece subtypeForResource; int32_t subtypeLen = static_cast<int32_t>(uprv_strlen(builtinUnit.getSubtype())); if (subtypeLen > 7 && uprv_strcmp(builtinUnit.getSubtype() + subtypeLen - 7, "-person") == 0) { subtypeForResource = {builtinUnit.getSubtype(), subtypeLen - 7}; } else { subtypeForResource = builtinUnit.getSubtype(); } CharString key; key.append("units/", status); key.append(builtinUnit.getType(), status); key.append("/", status); key.append(subtypeForResource, status); key.append("/gender", status); UErrorCode localStatus = status; int32_t resultLen = 0; const UChar *result = ures_getStringByKeyWithFallback(unitsBundle.getAlias(), key.data(), &resultLen, &localStatus); if (U_SUCCESS(localStatus)) { status = localStatus; return UnicodeString(true, result, resultLen); } else { // TODO(icu-units#28): "$unitRes/gender" does not exist. Do we want to // check whether the parent "$unitRes" exists? Then we could return // U_MISSING_RESOURCE_ERROR for incorrect usage (e.g. builtinUnit not // being a builtin). return {}; } } // Loads data from a resource tree with paths matching // $key/$pluralForm/$gender/$case, with lateral inheritance for missing cases // and genders. // // An InflectedPluralSink is configured to load data for a specific gender and // case. It loads all plural forms, because selection between plural forms is // dependent upon the value being formatted. // // See data/unit/de.txt and data/unit/fr.txt for examples - take a look at // units/compound/power2: German has case, French has differences for gender, // but no case. // // TODO(icu-units#138): Conceptually similar to PluralTableSink, however the // tree structures are different. After homogenizing the structures, we may be // able to unify the two classes. // // TODO: Spec violation: expects presence of "count" - does not fallback to an // absent "count"! If this fallback were added, getCompoundValue could be // superseded? class InflectedPluralSink : public ResourceSink { public: // Accepts `char*` rather than StringPiece because // ResourceTable::findValue(...) requires a null-terminated `char*`. // // NOTE: outArray MUST have a length of at least ARRAY_LENGTH. No bounds // checking is performed. explicit InflectedPluralSink(const char *gender, const char *caseVariant, UnicodeString *outArray) : gender(gender), caseVariant(caseVariant), outArray(outArray) { // Initialize the array to bogus strings. for (int32_t i = 0; i < ARRAY_LENGTH; i++) { outArray[i].setToBogus(); } } // See ResourceSink::put(). void put(const char *key, ResourceValue &value, UBool /*noFallback*/, UErrorCode &status) U_OVERRIDE { ResourceTable pluralsTable = value.getTable(status); if (U_FAILURE(status)) { return; } for (int32_t i = 0; pluralsTable.getKeyAndValue(i, key, value); ++i) { int32_t pluralIndex = getIndex(key, status); if (U_FAILURE(status)) { return; } if (!outArray[pluralIndex].isBogus()) { // We already have a pattern continue; } ResourceTable genderTable = value.getTable(status); ResourceTable caseTable; // This instance has to outlive `value` if (loadForPluralForm(genderTable, caseTable, value, status)) { outArray[pluralIndex] = value.getUnicodeString(status); } } } private: // Tries to load data for the configured gender from `genderTable`. Returns // true if found, returning the data in `value`. The returned data will be // for the configured gender if found, falling back to "neuter" and // no-gender if not. The caseTable parameter holds the intermediate // ResourceTable for the sake of lifetime management. bool loadForPluralForm(const ResourceTable &genderTable, ResourceTable &caseTable, ResourceValue &value, UErrorCode &status) { if (uprv_strcmp(gender, "") != 0) { if (loadForGender(genderTable, gender, caseTable, value, status)) { return true; } if (uprv_strcmp(gender, "neuter") != 0 && loadForGender(genderTable, "neuter", caseTable, value, status)) { return true; } } if (loadForGender(genderTable, "_", caseTable, value, status)) { return true; } return false; } // Tries to load data for the given gender from `genderTable`. Returns true // if found, returning the data in `value`. The returned data will be for // the configured case if found, falling back to "nominative" and no-case if // not. bool loadForGender(const ResourceTable &genderTable, const char *genderVal, ResourceTable &caseTable, ResourceValue &value, UErrorCode &status) { if (!genderTable.findValue(genderVal, value)) { return false; } caseTable = value.getTable(status); if (uprv_strcmp(caseVariant, "") != 0) { if (loadForCase(caseTable, caseVariant, value)) { return true; } if (uprv_strcmp(caseVariant, "nominative") != 0 && loadForCase(caseTable, "nominative", value)) { return true; } } if (loadForCase(caseTable, "_", value)) { return true; } return false; } // Tries to load data for the given case from `caseTable`. Returns true if // found, returning the data in `value`. bool loadForCase(const ResourceTable &caseTable, const char *caseValue, ResourceValue &value) { if (!caseTable.findValue(caseValue, value)) { return false; } return true; } const char *gender; const char *caseVariant; UnicodeString *outArray; }; // Fetches localised formatting patterns for the given subKey. See documentation // for InflectedPluralSink for details. // // Data is loaded for the appropriate unit width, with missing data filled in // from unitsShort. void getInflectedMeasureData(StringPiece subKey, const Locale &locale, const UNumberUnitWidth &width, const char *gender, const char *caseVariant, UnicodeString *outArray, UErrorCode &status) { InflectedPluralSink sink(gender, caseVariant, outArray); LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, locale.getName(), &status)); if (U_FAILURE(status)) { return; } CharString key; key.append("units", status); if (width == UNUM_UNIT_WIDTH_NARROW) { key.append("Narrow", status); } else if (width == UNUM_UNIT_WIDTH_SHORT) { key.append("Short", status); } key.append("/", status); key.append(subKey, status); UErrorCode localStatus = status; ures_getAllItemsWithFallback(unitsBundle.getAlias(), key.data(), sink, localStatus); if (width == UNUM_UNIT_WIDTH_SHORT) { status = localStatus; return; } // TODO(ICU-13353): The fallback to short does not work in ICU4C. // Manually fall back to short (this is done automatically in Java). key.clear(); key.append("unitsShort/", status); key.append(subKey, status); ures_getAllItemsWithFallback(unitsBundle.getAlias(), key.data(), sink, status); } class PluralTableSink : public ResourceSink { public: // NOTE: outArray MUST have a length of at least ARRAY_LENGTH. No bounds // checking is performed. explicit PluralTableSink(UnicodeString *outArray) : outArray(outArray) { // Initialize the array to bogus strings. for (int32_t i = 0; i < ARRAY_LENGTH; i++) { outArray[i].setToBogus(); } } void put(const char *key, ResourceValue &value, UBool /*noFallback*/, UErrorCode &status) U_OVERRIDE { ResourceTable pluralsTable = value.getTable(status); if (U_FAILURE(status)) { return; } for (int32_t i = 0; pluralsTable.getKeyAndValue(i, key, value); ++i) { if (uprv_strcmp(key, "case") == 0) { continue; } int32_t index = getIndex(key, status); if (U_FAILURE(status)) { return; } if (!outArray[index].isBogus()) { continue; } outArray[index] = value.getUnicodeString(status); if (U_FAILURE(status)) { return; } } } private: UnicodeString *outArray; }; /** * Populates outArray with `locale`-specific values for `unit` through use of * PluralTableSink. Only the set of basic units are supported! * * Reading from resources *unitsNarrow* and *unitsShort* (for width * UNUM_UNIT_WIDTH_NARROW), or just *unitsShort* (for width * UNUM_UNIT_WIDTH_SHORT). For other widths, it reads just "units". * * @param unit must be a built-in unit, i.e. must have a type and subtype, * listed in gTypes and gSubTypes in measunit.cpp. * @param unitDisplayCase the empty string and "nominative" are treated the * same. For other cases, strings for the requested case are used if found. * (For any missing case-specific data, we fall back to nominative.) * @param outArray must be of fixed length ARRAY_LENGTH. */ void getMeasureData(const Locale &locale, const MeasureUnit &unit, const UNumberUnitWidth &width, const char *unitDisplayCase, UnicodeString *outArray, UErrorCode &status) { PluralTableSink sink(outArray); LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, locale.getName(), &status)); if (U_FAILURE(status)) { return; } CharString subKey; subKey.append("/", status); subKey.append(unit.getType(), status); subKey.append("/", status); // Map duration-year-person, duration-week-person, etc. to duration-year, duration-week, ... // TODO(ICU-20400): Get duration-*-person data properly with aliases. int32_t subtypeLen = static_cast<int32_t>(uprv_strlen(unit.getSubtype())); if (subtypeLen > 7 && uprv_strcmp(unit.getSubtype() + subtypeLen - 7, "-person") == 0) { subKey.append({unit.getSubtype(), subtypeLen - 7}, status); } else { subKey.append({unit.getSubtype(), subtypeLen}, status); } if (width != UNUM_UNIT_WIDTH_FULL_NAME) { UErrorCode localStatus = status; CharString genderKey; genderKey.append("units", localStatus); genderKey.append(subKey, localStatus); genderKey.append("/gender", localStatus); StackUResourceBundle fillIn; ures_getByKeyWithFallback(unitsBundle.getAlias(), genderKey.data(), fillIn.getAlias(), &localStatus); outArray[GENDER_INDEX] = ures_getUnicodeString(fillIn.getAlias(), &localStatus); } CharString key; key.append("units", status); if (width == UNUM_UNIT_WIDTH_NARROW) { key.append("Narrow", status); } else if (width == UNUM_UNIT_WIDTH_SHORT) { key.append("Short", status); } key.append(subKey, status); // Grab desired case first, if available. Then grab no-case data to fill in // the gaps. if (width == UNUM_UNIT_WIDTH_FULL_NAME && unitDisplayCase[0] != 0) { CharString caseKey; caseKey.append(key, status); caseKey.append("/case/", status); caseKey.append(unitDisplayCase, status); UErrorCode localStatus = U_ZERO_ERROR; // TODO(icu-units#138): our fallback logic is not spec-compliant: // lateral fallback should happen before locale fallback. Switch to // getInflectedMeasureData after homogenizing data format? Find a unit // test case that demonstrates the incorrect fallback logic (via // regional variant of an inflected language?) ures_getAllItemsWithFallback(unitsBundle.getAlias(), caseKey.data(), sink, localStatus); } // TODO(icu-units#138): our fallback logic is not spec-compliant: we // check the given case, then go straight to the no-case data. The spec // states we should first look for case="nominative". As part of #138, // either get the spec changed, or add unit tests that warn us if // case="nominative" data differs from no-case data? UErrorCode localStatus = U_ZERO_ERROR; ures_getAllItemsWithFallback(unitsBundle.getAlias(), key.data(), sink, localStatus); if (width == UNUM_UNIT_WIDTH_SHORT) { if (U_FAILURE(localStatus)) { status = localStatus; } return; } // TODO(ICU-13353): The fallback to short does not work in ICU4C. // Manually fall back to short (this is done automatically in Java). key.clear(); key.append("unitsShort", status); key.append(subKey, status); ures_getAllItemsWithFallback(unitsBundle.getAlias(), key.data(), sink, status); } // NOTE: outArray MUST have a length of at least ARRAY_LENGTH. void getCurrencyLongNameData(const Locale &locale, const CurrencyUnit &currency, UnicodeString *outArray, UErrorCode &status) { // In ICU4J, this method gets a CurrencyData from CurrencyData.provider. // TODO(ICU4J): Implement this without going through CurrencyData, like in ICU4C? PluralTableSink sink(outArray); LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_CURR, locale.getName(), &status)); if (U_FAILURE(status)) { return; } ures_getAllItemsWithFallback(unitsBundle.getAlias(), "CurrencyUnitPatterns", sink, status); if (U_FAILURE(status)) { return; } for (int32_t i = 0; i < StandardPlural::Form::COUNT; i++) { UnicodeString &pattern = outArray[i]; if (pattern.isBogus()) { continue; } int32_t longNameLen = 0; const char16_t *longName = ucurr_getPluralName( currency.getISOCurrency(), locale.getName(), nullptr /* isChoiceFormat */, StandardPlural::getKeyword(static_cast<StandardPlural::Form>(i)), &longNameLen, &status); // Example pattern from data: "{0} {1}" // Example output after find-and-replace: "{0} US dollars" pattern.findAndReplace(UnicodeString(u"{1}"), UnicodeString(longName, longNameLen)); } } UnicodeString getCompoundValue(StringPiece compoundKey, const Locale &locale, const UNumberUnitWidth &width, UErrorCode &status) { LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, locale.getName(), &status)); if (U_FAILURE(status)) { return {}; } CharString key; key.append("units", status); if (width == UNUM_UNIT_WIDTH_NARROW) { key.append("Narrow", status); } else if (width == UNUM_UNIT_WIDTH_SHORT) { key.append("Short", status); } key.append("/compound/", status); key.append(compoundKey, status); UErrorCode localStatus = status; int32_t len = 0; const UChar *ptr = ures_getStringByKeyWithFallback(unitsBundle.getAlias(), key.data(), &len, &localStatus); if (U_FAILURE(localStatus) && width != UNUM_UNIT_WIDTH_SHORT) { // Fall back to short, which contains more compound data key.clear(); key.append("unitsShort/compound/", status); key.append(compoundKey, status); ptr = ures_getStringByKeyWithFallback(unitsBundle.getAlias(), key.data(), &len, &status); } else { status = localStatus; } if (U_FAILURE(status)) { return {}; } return UnicodeString(ptr, len); } /** * Loads and applies deriveComponent rules from CLDR's grammaticalFeatures.xml. * * Consider a deriveComponent rule that looks like this: * * <deriveComponent feature="case" structure="per" value0="compound" value1="nominative"/> * * Instantiating an instance as follows: * * DerivedComponents d(loc, "case", "per"); * * Applying the rule in the XML element above, `d.value0("foo")` will be "foo", * and `d.value1("foo")` will be "nominative". * * The values returned by value0(...) and value1(...) are valid only while the * instance exists. In case of any kind of failure, value0(...) and value1(...) * will return "". */ class DerivedComponents { public: /** * Constructor. * * The feature and structure parameters must be null-terminated. The string * referenced by compoundValue must exist for longer than the * DerivedComponents instance. */ DerivedComponents(const Locale &locale, const char *feature, const char *structure) { StackUResourceBundle derivationsBundle, stackBundle; ures_openDirectFillIn(derivationsBundle.getAlias(), NULL, "grammaticalFeatures", &status); ures_getByKey(derivationsBundle.getAlias(), "grammaticalData", derivationsBundle.getAlias(), &status); ures_getByKey(derivationsBundle.getAlias(), "derivations", derivationsBundle.getAlias(), &status); if (U_FAILURE(status)) { return; } UErrorCode localStatus = U_ZERO_ERROR; // TODO(icu-units#28): use standard normal locale resolution algorithms // rather than just grabbing language: ures_getByKey(derivationsBundle.getAlias(), locale.getLanguage(), stackBundle.getAlias(), &localStatus); // TODO(icu-units#28): // - code currently assumes if the locale exists, the rules are there - // instead of falling back to root when the requested rule is missing. // - investigate ures.h functions, see if one that uses res_findResource() // might be better (or use res_findResource directly), or maybe help // improve ures documentation to guide function selection? if (localStatus == U_MISSING_RESOURCE_ERROR) { ures_getByKey(derivationsBundle.getAlias(), "root", stackBundle.getAlias(), &status); } else { status = localStatus; } ures_getByKey(stackBundle.getAlias(), "component", stackBundle.getAlias(), &status); ures_getByKey(stackBundle.getAlias(), feature, stackBundle.getAlias(), &status); ures_getByKey(stackBundle.getAlias(), structure, stackBundle.getAlias(), &status); UnicodeString val0 = ures_getUnicodeStringByIndex(stackBundle.getAlias(), 0, &status); UnicodeString val1 = ures_getUnicodeStringByIndex(stackBundle.getAlias(), 1, &status); if (U_SUCCESS(status)) { if (val0.compare(UnicodeString(u"compound")) == 0) { compound0_ = true; } else { compound0_ = false; value0_.appendInvariantChars(val0, status); } if (val1.compare(UnicodeString(u"compound")) == 0) { compound1_ = true; } else { compound1_ = false; value1_.appendInvariantChars(val1, status); } } } // Returns a StringPiece that is only valid as long as the instance exists. StringPiece value0(const StringPiece compoundValue) const { return compound0_ ? compoundValue : value0_.toStringPiece(); } // Returns a StringPiece that is only valid as long as the instance exists. StringPiece value1(const StringPiece compoundValue) const { return compound1_ ? compoundValue : value1_.toStringPiece(); } // Returns a char* that is only valid as long as the instance exists. const char *value0(const char *compoundValue) const { return compound0_ ? compoundValue : value0_.data(); } // Returns a char* that is only valid as long as the instance exists. const char *value1(const char *compoundValue) const { return compound1_ ? compoundValue : value1_.data(); } private: UErrorCode status = U_ZERO_ERROR; // Holds strings referred to by value0 and value1; bool compound0_ = false, compound1_ = false; CharString value0_, value1_; }; // TODO(icu-units#28): test somehow? Associate with an ICU ticket for adding // testsuite support for testing with synthetic data? /** * Loads and returns the value in rules that look like these: * * <deriveCompound feature="gender" structure="per" value="0"/> * <deriveCompound feature="gender" structure="times" value="1"/> * * Currently a fake example, but spec compliant: * <deriveCompound feature="gender" structure="power" value="feminine"/> * * NOTE: If U_FAILURE(status), returns an empty string. */ UnicodeString getDeriveCompoundRule(Locale locale, const char *feature, const char *structure, UErrorCode &status) { StackUResourceBundle derivationsBundle, stackBundle; ures_openDirectFillIn(derivationsBundle.getAlias(), NULL, "grammaticalFeatures", &status); ures_getByKey(derivationsBundle.getAlias(), "grammaticalData", derivationsBundle.getAlias(), &status); ures_getByKey(derivationsBundle.getAlias(), "derivations", derivationsBundle.getAlias(), &status); // TODO: use standard normal locale resolution algorithms rather than just grabbing language: ures_getByKey(derivationsBundle.getAlias(), locale.getLanguage(), stackBundle.getAlias(), &status); // TODO: // - code currently assumes if the locale exists, the rules are there - // instead of falling back to root when the requested rule is missing. // - investigate ures.h functions, see if one that uses res_findResource() // might be better (or use res_findResource directly), or maybe help // improve ures documentation to guide function selection? if (status == U_MISSING_RESOURCE_ERROR) { status = U_ZERO_ERROR; ures_getByKey(derivationsBundle.getAlias(), "root", stackBundle.getAlias(), &status); } ures_getByKey(stackBundle.getAlias(), "compound", stackBundle.getAlias(), &status); ures_getByKey(stackBundle.getAlias(), feature, stackBundle.getAlias(), &status); UnicodeString uVal = ures_getUnicodeStringByKey(stackBundle.getAlias(), structure, &status); if (U_FAILURE(status)) { return {}; } U_ASSERT(!uVal.isBogus()); return uVal; } // Returns the gender string for structures following these rules: // // <deriveCompound feature="gender" structure="per" value="0"/> // <deriveCompound feature="gender" structure="times" value="1"/> // // Fake example: // <deriveCompound feature="gender" structure="power" value="feminine"/> // // data0 and data1 should be pattern arrays (UnicodeString[ARRAY_SIZE]) that // correspond to value="0" and value="1". // // Pass a nullptr to data1 if the structure has no concept of value="1" (e.g. // "prefix" doesn't). UnicodeString getDerivedGender(Locale locale, const char *structure, UnicodeString *data0, UnicodeString *data1, UErrorCode &status) { UnicodeString val = getDeriveCompoundRule(locale, "gender", structure, status); if (val.length() == 1) { switch (val[0]) { case u'0': return data0[GENDER_INDEX]; case u'1': if (data1 == nullptr) { return {}; } return data1[GENDER_INDEX]; } } return val; } //////////////////////// /// END DATA LOADING /// //////////////////////// // TODO: promote this somewhere? It's based on patternprops.cpp' trimWhitespace const UChar *trimSpaceChars(const UChar *s, int32_t &length) { if (length <= 0 || (!u_isJavaSpaceChar(s[0]) && !u_isJavaSpaceChar(s[length - 1]))) { return s; } int32_t start = 0; int32_t limit = length; while (start < limit && u_isJavaSpaceChar(s[start])) { ++start; } if (start < limit) { // There is non-white space at start; we will not move limit below that, // so we need not test start<limit in the loop. while (u_isJavaSpaceChar(s[limit - 1])) { --limit; } } length = limit - start; return s + start; } /** * Calculates the gender of an arbitrary unit: this is the *second* * implementation of an algorithm to do this: * * Gender is also calculated in "processPatternTimes": that code path is "bottom * up", loading the gender for every component of a compound unit (at the same * time as loading the Long Names formatting patterns), even if the gender is * unneeded, then combining the single units' genders into the compound unit's * gender, according to the rules. This algorithm does a lazier "top-down" * evaluation, starting with the compound unit, calculating which single unit's * gender is needed by breaking it down according to the rules, and then loading * only the gender of the one single unit who's gender is needed. * * For future refactorings: * 1. we could drop processPatternTimes' gender calculation and just call this * function: for UNUM_UNIT_WIDTH_FULL_NAME, the unit gender is in the very * same table as the formatting patterns, so loading it then may be * efficient. For other unit widths however, it needs to be explicitly looked * up anyway. * 2. alternatively, if CLDR is providing all the genders we need such that we * don't need to calculate them in ICU anymore, we could drop this function * and keep only processPatternTimes' calculation. (And optimise it a bit?) * * @param locale The desired locale. * @param unit The measure unit to calculate the gender for. * @return The gender string for the unit, or an empty string if unknown or * ungendered. */ UnicodeString calculateGenderForUnit(const Locale &locale, const MeasureUnit &unit, UErrorCode &status) { MeasureUnitImpl impl; const MeasureUnitImpl& mui = MeasureUnitImpl::forMeasureUnit(unit, impl, status); int32_t singleUnitIndex = 0; if (mui.complexity == UMEASURE_UNIT_COMPOUND) { int32_t startSlice = 0; // inclusive int32_t endSlice = mui.singleUnits.length()-1; U_ASSERT(endSlice > 0); // Else it would not be COMPOUND if (mui.singleUnits[endSlice]->dimensionality < 0) { // We have a -per- construct UnicodeString perRule = getDeriveCompoundRule(locale, "gender", "per", status); if (perRule.length() != 1) { // Fixed gender for -per- units return perRule; } if (perRule[0] == u'1') { // Find the start of the denominator. We already know there is one. while (mui.singleUnits[startSlice]->dimensionality >= 0) { startSlice++; } } else { // Find the end of the numerator while (endSlice >= 0 && mui.singleUnits[endSlice]->dimensionality < 0) { endSlice--; } if (endSlice < 0) { // We have only a denominator, e.g. "per-second". // TODO(icu-units#28): find out what gender to use in the // absence of a first value - mentioned in CLDR-14253. return {}; } } } if (endSlice > startSlice) { // We have a -times- construct UnicodeString timesRule = getDeriveCompoundRule(locale, "gender", "times", status); if (timesRule.length() != 1) { // Fixed gender for -times- units return timesRule; } if (timesRule[0] == u'0') { endSlice = startSlice; } else { // We assume timesRule[0] == u'1' startSlice = endSlice; } } U_ASSERT(startSlice == endSlice); singleUnitIndex = startSlice; } else if (mui.complexity == UMEASURE_UNIT_MIXED) { status = U_INTERNAL_PROGRAM_ERROR; return {}; } else { U_ASSERT(mui.complexity == UMEASURE_UNIT_SINGLE); U_ASSERT(mui.singleUnits.length() == 1); } // Now we know which singleUnit's gender we want const SingleUnitImpl *singleUnit = mui.singleUnits[singleUnitIndex]; // Check for any power-prefix gender override: if (std::abs(singleUnit->dimensionality) != 1) { UnicodeString powerRule = getDeriveCompoundRule(locale, "gender", "power", status); if (powerRule.length() != 1) { // Fixed gender for -powN- units return powerRule; } // powerRule[0] == u'0'; u'1' not currently in spec. } // Check for any SI and binary prefix gender override: if (std::abs(singleUnit->dimensionality) != 1) { UnicodeString prefixRule = getDeriveCompoundRule(locale, "gender", "prefix", status); if (prefixRule.length() != 1) { // Fixed gender for -powN- units return prefixRule; } // prefixRule[0] == u'0'; u'1' not currently in spec. } // Now we've boiled it down to the gender of one simple unit identifier: return getGenderForBuiltin(locale, MeasureUnit::forIdentifier(singleUnit->getSimpleUnitID(), status), status); } void maybeCalculateGender(const Locale &locale, const MeasureUnit &unitRef, UnicodeString *outArray, UErrorCode &status) { if (outArray[GENDER_INDEX].isBogus()) { UnicodeString meterGender = getGenderForBuiltin(locale, MeasureUnit::getMeter(), status); if (meterGender.isEmpty()) { // No gender for meter: assume ungendered language return; } // We have a gendered language, but are lacking gender for unitRef. outArray[GENDER_INDEX] = calculateGenderForUnit(locale, unitRef, status); } } } // namespace void LongNameHandler::forMeasureUnit(const Locale &loc, const MeasureUnit &unitRef, const UNumberUnitWidth &width, const char *unitDisplayCase, const PluralRules *rules, const MicroPropsGenerator *parent, LongNameHandler *fillIn, UErrorCode &status) { // From https://unicode.org/reports/tr35/tr35-general.html#compound-units - // Points 1 and 2 are mostly handled by MeasureUnit: // // 1. If the unitId is empty or invalid, fail // 2. Put the unitId into normalized order U_ASSERT(fillIn != nullptr); if (uprv_strcmp(unitRef.getType(), "") != 0) { // Handling built-in units: // // 3. Set result to be getValue(unitId with length, pluralCategory, caseVariant) // - If result is not empty, return it UnicodeString simpleFormats[ARRAY_LENGTH]; getMeasureData(loc, unitRef, width, unitDisplayCase, simpleFormats, status); maybeCalculateGender(loc, unitRef, simpleFormats, status); if (U_FAILURE(status)) { return; } fillIn->rules = rules; fillIn->parent = parent; fillIn->simpleFormatsToModifiers(simpleFormats, {UFIELD_CATEGORY_NUMBER, UNUM_MEASURE_UNIT_FIELD}, status); if (!simpleFormats[GENDER_INDEX].isBogus()) { fillIn->gender = getGenderString(simpleFormats[GENDER_INDEX], status); } return; // TODO(icu-units#145): figure out why this causes a failure in // format/MeasureFormatTest/TestIndividualPluralFallback and other // tests, when it should have been an alternative for the lines above: // forArbitraryUnit(loc, unitRef, width, unitDisplayCase, fillIn, status); // fillIn->rules = rules; // fillIn->parent = parent; // return; } else { // Check if it is a MeasureUnit this constructor handles: this // constructor does not handle mixed units U_ASSERT(unitRef.getComplexity(status) != UMEASURE_UNIT_MIXED); forArbitraryUnit(loc, unitRef, width, unitDisplayCase, fillIn, status); fillIn->rules = rules; fillIn->parent = parent; return; } } void LongNameHandler::forArbitraryUnit(const Locale &loc, const MeasureUnit &unitRef, const UNumberUnitWidth &width, const char *unitDisplayCase, LongNameHandler *fillIn, UErrorCode &status) { if (U_FAILURE(status)) { return; } if (fillIn == nullptr) { status = U_INTERNAL_PROGRAM_ERROR; return; } // Numbered list items are from the algorithms at // https://unicode.org/reports/tr35/tr35-general.html#compound-units: // // 4. Divide the unitId into numerator (the part before the "-per-") and // denominator (the part after the "-per-). If both are empty, fail MeasureUnitImpl unit; MeasureUnitImpl perUnit; { MeasureUnitImpl fullUnit = MeasureUnitImpl::forMeasureUnitMaybeCopy(unitRef, status); if (U_FAILURE(status)) { return; } for (int32_t i = 0; i < fullUnit.singleUnits.length(); i++) { SingleUnitImpl *subUnit = fullUnit.singleUnits[i]; if (subUnit->dimensionality > 0) { unit.appendSingleUnit(*subUnit, status); } else { subUnit->dimensionality *= -1; perUnit.appendSingleUnit(*subUnit, status); } } } // TODO(icu-units#28): check placeholder logic, see if it needs to be // present here instead of only in processPatternTimes: // // 5. Set both globalPlaceholder and globalPlaceholderPosition to be empty DerivedComponents derivedPerCases(loc, "case", "per"); // 6. numeratorUnitString UnicodeString numeratorUnitData[ARRAY_LENGTH]; processPatternTimes(std::move(unit), loc, width, derivedPerCases.value0(unitDisplayCase), numeratorUnitData, status); // 7. denominatorUnitString UnicodeString denominatorUnitData[ARRAY_LENGTH]; processPatternTimes(std::move(perUnit), loc, width, derivedPerCases.value1(unitDisplayCase), denominatorUnitData, status); // TODO(icu-units#139): // - implement DerivedComponents for "plural/times" and "plural/power": // French has different rules, we'll be producing the wrong results // currently. (Prove via tests!) // - implement DerivedComponents for "plural/per", "plural/prefix", // "case/times", "case/power", and "case/prefix" - although they're // currently hardcoded. Languages with different rules are surely on the // way. // // Currently we only use "case/per", "plural/times", "case/times", and // "case/power". // // This may have impact on multiSimpleFormatsToModifiers(...) below too? // These rules are currently (ICU 69) all the same and hard-coded below. UnicodeString perUnitPattern; if (!denominatorUnitData[PER_INDEX].isBogus()) { // If we have no denominator, we obtain the empty string: perUnitPattern = denominatorUnitData[PER_INDEX]; } else { // 8. Set perPattern to be getValue([per], locale, length) UnicodeString rawPerUnitFormat = getCompoundValue("per", loc, width, status); // rawPerUnitFormat is something like "{0} per {1}"; we need to substitute in the secondary unit. SimpleFormatter perPatternFormatter(rawPerUnitFormat, 2, 2, status); if (U_FAILURE(status)) { return; } // Plural and placeholder handling for 7. denominatorUnitString: // TODO(icu-units#139): hardcoded: // <deriveComponent feature="plural" structure="per" value0="compound" value1="one"/> UnicodeString denominatorFormat = getWithPlural(denominatorUnitData, StandardPlural::Form::ONE, status); // Some "one" pattern may not contain "{0}". For example in "ar" or "ne" locale. SimpleFormatter denominatorFormatter(denominatorFormat, 0, 1, status); if (U_FAILURE(status)) { return; } UnicodeString denominatorPattern = denominatorFormatter.getTextWithNoArguments(); int32_t trimmedLen = denominatorPattern.length(); const UChar *trimmed = trimSpaceChars(denominatorPattern.getBuffer(), trimmedLen); UnicodeString denominatorString(false, trimmed, trimmedLen); // 9. If the denominatorString is empty, set result to // [numeratorString], otherwise set result to format(perPattern, // numeratorString, denominatorString) // // TODO(icu-units#28): Why does UnicodeString need to be explicit in the // following line? perPatternFormatter.format(UnicodeString(u"{0}"), denominatorString, perUnitPattern, status); if (U_FAILURE(status)) { return; } } if (perUnitPattern.length() == 0) { fillIn->simpleFormatsToModifiers(numeratorUnitData, {UFIELD_CATEGORY_NUMBER, UNUM_MEASURE_UNIT_FIELD}, status); } else { fillIn->multiSimpleFormatsToModifiers(numeratorUnitData, perUnitPattern, {UFIELD_CATEGORY_NUMBER, UNUM_MEASURE_UNIT_FIELD}, status); } // Gender // // TODO(icu-units#28): find out what gender to use in the absence of a first // value - e.g. what's the gender of "per-second"? Mentioned in CLDR-14253. // // gender/per deriveCompound rules don't say: // <deriveCompound feature="gender" structure="per" value="0"/> <!-- gender(gram-per-meter) ← gender(gram) --> fillIn->gender = getGenderString( getDerivedGender(loc, "per", numeratorUnitData, denominatorUnitData, status), status); } void LongNameHandler::processPatternTimes(MeasureUnitImpl &&productUnit, Locale loc, const UNumberUnitWidth &width, const char *caseVariant, UnicodeString *outArray, UErrorCode &status) { if (U_FAILURE(status)) { return; } if (productUnit.complexity == UMEASURE_UNIT_MIXED) { // These are handled by MixedUnitLongNameHandler status = U_UNSUPPORTED_ERROR; return; } #if U_DEBUG for (int32_t pluralIndex = 0; pluralIndex < ARRAY_LENGTH; pluralIndex++) { U_ASSERT(outArray[pluralIndex].length() == 0); U_ASSERT(!outArray[pluralIndex].isBogus()); } #endif if (productUnit.identifier.isEmpty()) { // TODO(icu-units#28): consider when serialize should be called. // identifier might also be empty for MeasureUnit(). productUnit.serialize(status); } if (U_FAILURE(status)) { return; } if (productUnit.identifier.length() == 0) { // MeasureUnit(): no units: return empty strings. return; } MeasureUnit builtinUnit; if (MeasureUnit::findBySubType(productUnit.identifier.toStringPiece(), &builtinUnit)) { // TODO(icu-units#145): spec doesn't cover builtin-per-builtin, it // breaks them all down. Do we want to drop this? // - findBySubType isn't super efficient, if we skip it and go to basic // singles, we don't have to construct MeasureUnit's anymore. // - Check all the existing unit tests that fail without this: is it due // to incorrect fallback via getMeasureData? // - Do those unit tests cover this code path representatively? if (builtinUnit != MeasureUnit()) { getMeasureData(loc, builtinUnit, width, caseVariant, outArray, status); maybeCalculateGender(loc, builtinUnit, outArray, status); } return; } // 2. Set timesPattern to be getValue(times, locale, length) UnicodeString timesPattern = getCompoundValue("times", loc, width, status); SimpleFormatter timesPatternFormatter(timesPattern, 2, 2, status); if (U_FAILURE(status)) { return; } PlaceholderPosition globalPlaceholder[ARRAY_LENGTH]; UChar globalJoinerChar = 0; // Numbered list items are from the algorithms at // https://unicode.org/reports/tr35/tr35-general.html#compound-units: // // pattern(...) point 5: // - Set both globalPlaceholder and globalPlaceholderPosition to be empty // // 3. Set result to be empty for (int32_t pluralIndex = 0; pluralIndex < ARRAY_LENGTH; pluralIndex++) { // Initial state: empty string pattern, via all falling back to OTHER: if (pluralIndex == StandardPlural::Form::OTHER) { outArray[pluralIndex].remove(); } else { outArray[pluralIndex].setToBogus(); } globalPlaceholder[pluralIndex] = PH_EMPTY; } // Empty string represents "compound" (propagate the plural form). const char *pluralCategory = ""; DerivedComponents derivedTimesPlurals(loc, "plural", "times"); DerivedComponents derivedTimesCases(loc, "case", "times"); DerivedComponents derivedPowerCases(loc, "case", "power"); // 4. For each single_unit in product_unit for (int32_t singleUnitIndex = 0; singleUnitIndex < productUnit.singleUnits.length(); singleUnitIndex++) { SingleUnitImpl *singleUnit = productUnit.singleUnits[singleUnitIndex]; const char *singlePluralCategory; const char *singleCaseVariant; // TODO(icu-units#28): ensure we have unit tests that change/fail if we // assign incorrect case variants here: if (singleUnitIndex < productUnit.singleUnits.length() - 1) { // 4.1. If hasMultiple singlePluralCategory = derivedTimesPlurals.value0(pluralCategory); singleCaseVariant = derivedTimesCases.value0(caseVariant); pluralCategory = derivedTimesPlurals.value1(pluralCategory); caseVariant = derivedTimesCases.value1(caseVariant); } else { singlePluralCategory = derivedTimesPlurals.value1(pluralCategory); singleCaseVariant = derivedTimesCases.value1(caseVariant); } // 4.2. Get the gender of that single_unit MeasureUnit simpleUnit; if (!MeasureUnit::findBySubType(singleUnit->getSimpleUnitID(), &simpleUnit)) { // Ideally all simple units should be known, but they're not: // 100-kilometer is internally treated as a simple unit, but it is // not a built-in unit and does not have formatting data in CLDR 39. // // TODO(icu-units#28): test (desirable) invariants in unit tests. status = U_UNSUPPORTED_ERROR; return; } const char *gender = getGenderString(getGenderForBuiltin(loc, simpleUnit, status), status); // 4.3. If singleUnit starts with a dimensionality_prefix, such as 'square-' U_ASSERT(singleUnit->dimensionality > 0); int32_t dimensionality = singleUnit->dimensionality; UnicodeString dimensionalityPrefixPatterns[ARRAY_LENGTH]; if (dimensionality != 1) { // 4.3.1. set dimensionalityPrefixPattern to be // getValue(that dimensionality_prefix, locale, length, singlePluralCategory, singleCaseVariant, gender), // such as "{0} kwadratowym" CharString dimensionalityKey("compound/power", status); dimensionalityKey.appendNumber(dimensionality, status); getInflectedMeasureData(dimensionalityKey.toStringPiece(), loc, width, gender, singleCaseVariant, dimensionalityPrefixPatterns, status); if (U_FAILURE(status)) { // At the time of writing, only pow2 and pow3 are supported. // Attempting to format other powers results in a // U_RESOURCE_TYPE_MISMATCH. We convert the error if we // understand it: if (status == U_RESOURCE_TYPE_MISMATCH && dimensionality > 3) { status = U_UNSUPPORTED_ERROR; } return; } // TODO(icu-units#139): // 4.3.2. set singlePluralCategory to be power0(singlePluralCategory) // 4.3.3. set singleCaseVariant to be power0(singleCaseVariant) singleCaseVariant = derivedPowerCases.value0(singleCaseVariant); // 4.3.4. remove the dimensionality_prefix from singleUnit singleUnit->dimensionality = 1; } // 4.4. if singleUnit starts with an si_prefix, such as 'centi' UMeasurePrefix prefix = singleUnit->unitPrefix; UnicodeString prefixPattern; if (prefix != UMEASURE_PREFIX_ONE) { // 4.4.1. set siPrefixPattern to be getValue(that si_prefix, locale, // length), such as "centy{0}" CharString prefixKey; // prefixKey looks like "1024p3" or "10p-2": prefixKey.appendNumber(umeas_getPrefixBase(prefix), status); prefixKey.append('p', status); prefixKey.appendNumber(umeas_getPrefixPower(prefix), status); // Contains a pattern like "centy{0}". prefixPattern = getCompoundValue(prefixKey.toStringPiece(), loc, width, status); // 4.4.2. set singlePluralCategory to be prefix0(singlePluralCategory) // // TODO(icu-units#139): that refers to these rules: // <deriveComponent feature="plural" structure="prefix" value0="one" value1="compound"/> // though I'm not sure what other value they might end up having. // // 4.4.3. set singleCaseVariant to be prefix0(singleCaseVariant) // // TODO(icu-units#139): that refers to: // <deriveComponent feature="case" structure="prefix" value0="nominative" // value1="compound"/> but the prefix (value0) doesn't have case, the rest simply // propagates. // 4.4.4. remove the si_prefix from singleUnit singleUnit->unitPrefix = UMEASURE_PREFIX_ONE; } // 4.5. Set corePattern to be the getValue(singleUnit, locale, length, // singlePluralCategory, singleCaseVariant), such as "{0} metrem" UnicodeString singleUnitArray[ARRAY_LENGTH]; // At this point we are left with a Simple Unit: U_ASSERT(uprv_strcmp(singleUnit->build(status).getIdentifier(), singleUnit->getSimpleUnitID()) == 0); getMeasureData(loc, singleUnit->build(status), width, singleCaseVariant, singleUnitArray, status); if (U_FAILURE(status)) { // Shouldn't happen if we have data for all single units return; } // Calculate output gender if (!singleUnitArray[GENDER_INDEX].isBogus()) { U_ASSERT(!singleUnitArray[GENDER_INDEX].isEmpty()); UnicodeString uVal; if (prefix != UMEASURE_PREFIX_ONE) { singleUnitArray[GENDER_INDEX] = getDerivedGender(loc, "prefix", singleUnitArray, nullptr, status); } if (dimensionality != 1) { singleUnitArray[GENDER_INDEX] = getDerivedGender(loc, "power", singleUnitArray, nullptr, status); } UnicodeString timesGenderRule = getDeriveCompoundRule(loc, "gender", "times", status); if (timesGenderRule.length() == 1) { switch (timesGenderRule[0]) { case u'0': if (singleUnitIndex == 0) { U_ASSERT(outArray[GENDER_INDEX].isBogus()); outArray[GENDER_INDEX] = singleUnitArray[GENDER_INDEX]; } break; case u'1': if (singleUnitIndex == productUnit.singleUnits.length() - 1) { U_ASSERT(outArray[GENDER_INDEX].isBogus()); outArray[GENDER_INDEX] = singleUnitArray[GENDER_INDEX]; } } } else { if (outArray[GENDER_INDEX].isBogus()) { outArray[GENDER_INDEX] = timesGenderRule; } } } // Calculate resulting patterns for each plural form for (int32_t pluralIndex = 0; pluralIndex < StandardPlural::Form::COUNT; pluralIndex++) { StandardPlural::Form plural = static_cast<StandardPlural::Form>(pluralIndex); // singleUnitArray[pluralIndex] looks something like "{0} Meter" if (outArray[pluralIndex].isBogus()) { if (singleUnitArray[pluralIndex].isBogus()) { // Let the usual plural fallback mechanism take care of this // plural form continue; } else { // Since our singleUnit can have a plural form that outArray // doesn't yet have (relying on fallback to OTHER), we start // by grabbing it with the normal plural fallback mechanism outArray[pluralIndex] = getWithPlural(outArray, plural, status); if (U_FAILURE(status)) { return; } } } if (uprv_strcmp(singlePluralCategory, "") != 0) { plural = static_cast<StandardPlural::Form>(getIndex(singlePluralCategory, status)); } // 4.6. Extract(corePattern, coreUnit, placeholder, placeholderPosition) from that pattern. UnicodeString coreUnit; PlaceholderPosition placeholderPosition; UChar joinerChar; extractCorePattern(getWithPlural(singleUnitArray, plural, status), coreUnit, placeholderPosition, joinerChar); // 4.7 If the position is middle, then fail if (placeholderPosition == PH_MIDDLE) { status = U_UNSUPPORTED_ERROR; return; } // 4.8. If globalPlaceholder is empty if (globalPlaceholder[pluralIndex] == PH_EMPTY) { globalPlaceholder[pluralIndex] = placeholderPosition; globalJoinerChar = joinerChar; } else { // Expect all units involved to have the same placeholder position U_ASSERT(globalPlaceholder[pluralIndex] == placeholderPosition); // TODO(icu-units#28): Do we want to add a unit test that checks // for consistent joiner chars? Probably not, given how // inconsistent they are. File a CLDR ticket with examples? } // Now coreUnit would be just "Meter" // 4.9. If siPrefixPattern is not empty if (prefix != UMEASURE_PREFIX_ONE) { SimpleFormatter prefixCompiled(prefixPattern, 1, 1, status); if (U_FAILURE(status)) { return; } // 4.9.1. Set coreUnit to be the combineLowercasing(locale, length, siPrefixPattern, // coreUnit) UnicodeString tmp; // combineLowercasing(locale, length, prefixPattern, coreUnit) // // TODO(icu-units#28): run this only if prefixPattern does not // contain space characters - do languages "as", "bn", "hi", // "kk", etc have concepts of upper and lower case?: if (width == UNUM_UNIT_WIDTH_FULL_NAME) { coreUnit.toLower(loc); } prefixCompiled.format(coreUnit, tmp, status); if (U_FAILURE(status)) { return; } coreUnit = tmp; } // 4.10. If dimensionalityPrefixPattern is not empty if (dimensionality != 1) { SimpleFormatter dimensionalityCompiled( getWithPlural(dimensionalityPrefixPatterns, plural, status), 1, 1, status); if (U_FAILURE(status)) { return; } // 4.10.1. Set coreUnit to be the combineLowercasing(locale, length, // dimensionalityPrefixPattern, coreUnit) UnicodeString tmp; // combineLowercasing(locale, length, prefixPattern, coreUnit) // // TODO(icu-units#28): run this only if prefixPattern does not // contain space characters - do languages "as", "bn", "hi", // "kk", etc have concepts of upper and lower case?: if (width == UNUM_UNIT_WIDTH_FULL_NAME) { coreUnit.toLower(loc); } dimensionalityCompiled.format(coreUnit, tmp, status); if (U_FAILURE(status)) { return; } coreUnit = tmp; } if (outArray[pluralIndex].length() == 0) { // 4.11. If the result is empty, set result to be coreUnit outArray[pluralIndex] = coreUnit; } else { // 4.12. Otherwise set result to be format(timesPattern, result, coreUnit) UnicodeString tmp; timesPatternFormatter.format(outArray[pluralIndex], coreUnit, tmp, status); outArray[pluralIndex] = tmp; } } } for (int32_t pluralIndex = 0; pluralIndex < StandardPlural::Form::COUNT; pluralIndex++) { if (globalPlaceholder[pluralIndex] == PH_BEGINNING) { UnicodeString tmp; tmp.append(u"{0}", 3); if (globalJoinerChar != 0) { tmp.append(globalJoinerChar); } tmp.append(outArray[pluralIndex]); outArray[pluralIndex] = tmp; } else if (globalPlaceholder[pluralIndex] == PH_END) { if (globalJoinerChar != 0) { outArray[pluralIndex].append(globalJoinerChar); } outArray[pluralIndex].append(u"{0}", 3); } } } UnicodeString LongNameHandler::getUnitDisplayName( const Locale& loc, const MeasureUnit& unit, UNumberUnitWidth width, UErrorCode& status) { if (U_FAILURE(status)) { return ICU_Utility::makeBogusString(); } UnicodeString simpleFormats[ARRAY_LENGTH]; getMeasureData(loc, unit, width, "", simpleFormats, status); return simpleFormats[DNAM_INDEX]; } UnicodeString LongNameHandler::getUnitPattern( const Locale& loc, const MeasureUnit& unit, UNumberUnitWidth width, StandardPlural::Form pluralForm, UErrorCode& status) { if (U_FAILURE(status)) { return ICU_Utility::makeBogusString(); } UnicodeString simpleFormats[ARRAY_LENGTH]; getMeasureData(loc, unit, width, "", simpleFormats, status); // The above already handles fallback from other widths to short if (U_FAILURE(status)) { return ICU_Utility::makeBogusString(); } // Now handle fallback from other plural forms to OTHER return (!(simpleFormats[pluralForm]).isBogus())? simpleFormats[pluralForm]: simpleFormats[StandardPlural::Form::OTHER]; } LongNameHandler* LongNameHandler::forCurrencyLongNames(const Locale &loc, const CurrencyUnit &currency, const PluralRules *rules, const MicroPropsGenerator *parent, UErrorCode &status) { auto* result = new LongNameHandler(rules, parent); if (result == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return nullptr; } UnicodeString simpleFormats[ARRAY_LENGTH]; getCurrencyLongNameData(loc, currency, simpleFormats, status); if (U_FAILURE(status)) { return nullptr; } result->simpleFormatsToModifiers(simpleFormats, {UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD}, status); // TODO(icu-units#28): currency gender? return result; } void LongNameHandler::simpleFormatsToModifiers(const UnicodeString *simpleFormats, Field field, UErrorCode &status) { for (int32_t i = 0; i < StandardPlural::Form::COUNT; i++) { StandardPlural::Form plural = static_cast<StandardPlural::Form>(i); UnicodeString simpleFormat = getWithPlural(simpleFormats, plural, status); if (U_FAILURE(status)) { return; } SimpleFormatter compiledFormatter(simpleFormat, 0, 1, status); if (U_FAILURE(status)) { return; } fModifiers[i] = SimpleModifier(compiledFormatter, field, false, {this, SIGNUM_POS_ZERO, plural}); } } void LongNameHandler::multiSimpleFormatsToModifiers(const UnicodeString *leadFormats, UnicodeString trailFormat, Field field, UErrorCode &status) { SimpleFormatter trailCompiled(trailFormat, 1, 1, status); if (U_FAILURE(status)) { return; } for (int32_t i = 0; i < StandardPlural::Form::COUNT; i++) { StandardPlural::Form plural = static_cast<StandardPlural::Form>(i); UnicodeString leadFormat = getWithPlural(leadFormats, plural, status); if (U_FAILURE(status)) { return; } UnicodeString compoundFormat; if (leadFormat.length() == 0) { compoundFormat = trailFormat; } else { trailCompiled.format(leadFormat, compoundFormat, status); if (U_FAILURE(status)) { return; } } SimpleFormatter compoundCompiled(compoundFormat, 0, 1, status); if (U_FAILURE(status)) { return; } fModifiers[i] = SimpleModifier(compoundCompiled, field, false, {this, SIGNUM_POS_ZERO, plural}); } } void LongNameHandler::processQuantity(DecimalQuantity &quantity, MicroProps &micros, UErrorCode &status) const { if (parent != NULL) { parent->processQuantity(quantity, micros, status); } StandardPlural::Form pluralForm = utils::getPluralSafe(micros.rounder, rules, quantity, status); micros.modOuter = &fModifiers[pluralForm]; micros.gender = gender; } const Modifier* LongNameHandler::getModifier(Signum /*signum*/, StandardPlural::Form plural) const { return &fModifiers[plural]; } void MixedUnitLongNameHandler::forMeasureUnit(const Locale &loc, const MeasureUnit &mixedUnit, const UNumberUnitWidth &width, const char *unitDisplayCase, const PluralRules *rules, const MicroPropsGenerator *parent, MixedUnitLongNameHandler *fillIn, UErrorCode &status) { U_ASSERT(mixedUnit.getComplexity(status) == UMEASURE_UNIT_MIXED); U_ASSERT(fillIn != nullptr); if (U_FAILURE(status)) { return; } MeasureUnitImpl temp; const MeasureUnitImpl &impl = MeasureUnitImpl::forMeasureUnit(mixedUnit, temp, status); // Defensive, for production code: if (impl.complexity != UMEASURE_UNIT_MIXED) { // Should be using the normal LongNameHandler status = U_UNSUPPORTED_ERROR; return; } fillIn->fMixedUnitCount = impl.singleUnits.length(); fillIn->fMixedUnitData.adoptInstead(new UnicodeString[fillIn->fMixedUnitCount * ARRAY_LENGTH]); for (int32_t i = 0; i < fillIn->fMixedUnitCount; i++) { // Grab data for each of the components. UnicodeString *unitData = &fillIn->fMixedUnitData[i * ARRAY_LENGTH]; // TODO(CLDR-14502): check from the CLDR-14502 ticket whether this // propagation of unitDisplayCase is correct: getMeasureData(loc, impl.singleUnits[i]->build(status), width, unitDisplayCase, unitData, status); // TODO(ICU-21494): if we add support for gender for mixed units, we may // need maybeCalculateGender() here. } // TODO(icu-units#120): Make sure ICU doesn't output zero-valued // high-magnitude fields // * for mixed units count N, produce N listFormatters, one for each subset // that might be formatted. UListFormatterWidth listWidth = ULISTFMT_WIDTH_SHORT; if (width == UNUM_UNIT_WIDTH_NARROW) { listWidth = ULISTFMT_WIDTH_NARROW; } else if (width == UNUM_UNIT_WIDTH_FULL_NAME) { // This might be the same as SHORT in most languages: listWidth = ULISTFMT_WIDTH_WIDE; } fillIn->fListFormatter.adoptInsteadAndCheckErrorCode( ListFormatter::createInstance(loc, ULISTFMT_TYPE_UNITS, listWidth, status), status); // TODO(ICU-21494): grab gender of each unit, calculate the gender // associated with this list formatter, save it for later. fillIn->rules = rules; fillIn->parent = parent; // We need a localised NumberFormatter for the numbers of the bigger units // (providing Arabic numerals, for example). fillIn->fNumberFormatter = NumberFormatter::withLocale(loc); } void MixedUnitLongNameHandler::processQuantity(DecimalQuantity &quantity, MicroProps &micros, UErrorCode &status) const { U_ASSERT(fMixedUnitCount > 1); if (parent != nullptr) { parent->processQuantity(quantity, micros, status); } micros.modOuter = getMixedUnitModifier(quantity, micros, status); } const Modifier *MixedUnitLongNameHandler::getMixedUnitModifier(DecimalQuantity &quantity, MicroProps &micros, UErrorCode &status) const { if (micros.mixedMeasuresCount == 0) { U_ASSERT(micros.mixedMeasuresCount > 0); // Mixed unit: we must have more than one unit value status = U_UNSUPPORTED_ERROR; return &micros.helpers.emptyWeakModifier; } // Algorithm: // // For the mixed-units measurement of: "3 yard, 1 foot, 2.6 inch", we should // find "3 yard" and "1 foot" in micros.mixedMeasures. // // Obtain long-names with plural forms corresponding to measure values: // * {0} yards, {0} foot, {0} inches // // Format the integer values appropriately and modify with the format // strings: // - 3 yards, 1 foot // // Use ListFormatter to combine, with one placeholder: // - 3 yards, 1 foot and {0} inches // // Return a SimpleModifier for this pattern, letting the rest of the // pipeline take care of the remaining inches. LocalArray<UnicodeString> outputMeasuresList(new UnicodeString[fMixedUnitCount], status); if (U_FAILURE(status)) { return &micros.helpers.emptyWeakModifier; } StandardPlural::Form quantityPlural = StandardPlural::Form::OTHER; for (int32_t i = 0; i < micros.mixedMeasuresCount; i++) { DecimalQuantity fdec; // If numbers are negative, only the first number needs to have its // negative sign formatted. int64_t number = i > 0 ? std::abs(micros.mixedMeasures[i]) : micros.mixedMeasures[i]; if (micros.indexOfQuantity == i) { // Insert placeholder for `quantity` // If quantity is not the first value and quantity is negative if (micros.indexOfQuantity > 0 && quantity.isNegative()) { quantity.negate(); } StandardPlural::Form quantityPlural = utils::getPluralSafe(micros.rounder, rules, quantity, status); UnicodeString quantityFormatWithPlural = getWithPlural(&fMixedUnitData[i * ARRAY_LENGTH], quantityPlural, status); SimpleFormatter quantityFormatter(quantityFormatWithPlural, 0, 1, status); quantityFormatter.format(UnicodeString(u"{0}"), outputMeasuresList[i], status); } else { fdec.setToLong(number); StandardPlural::Form pluralForm = utils::getStandardPlural(rules, fdec); UnicodeString simpleFormat = getWithPlural(&fMixedUnitData[i * ARRAY_LENGTH], pluralForm, status); SimpleFormatter compiledFormatter(simpleFormat, 0, 1, status); UnicodeString num; auto appendable = UnicodeStringAppendable(num); fNumberFormatter.formatDecimalQuantity(fdec, status).appendTo(appendable, status); compiledFormatter.format(num, outputMeasuresList[i], status); } } // TODO(ICU-21494): implement gender for lists of mixed units. Presumably we // can set micros.gender to the gender associated with the list formatter in // use below (once we have correct support for that). And then document this // appropriately? "getMixedUnitModifier" doesn't sound like it would do // something like this. // Combine list into a "premixed" pattern UnicodeString premixedFormatPattern; fListFormatter->format(outputMeasuresList.getAlias(), fMixedUnitCount, premixedFormatPattern, status); SimpleFormatter premixedCompiled(premixedFormatPattern, 0, 1, status); if (U_FAILURE(status)) { return &micros.helpers.emptyWeakModifier; } micros.helpers.mixedUnitModifier = SimpleModifier(premixedCompiled, kUndefinedField, false, {this, SIGNUM_POS_ZERO, quantityPlural}); return &micros.helpers.mixedUnitModifier; } const Modifier *MixedUnitLongNameHandler::getModifier(Signum /*signum*/, StandardPlural::Form /*plural*/) const { // TODO(icu-units#28): investigate this method when investigating where // ModifierStore::getModifier() gets used. To be sure it remains // unreachable: UPRV_UNREACHABLE; return nullptr; } LongNameMultiplexer *LongNameMultiplexer::forMeasureUnits(const Locale &loc, const MaybeStackVector<MeasureUnit> &units, const UNumberUnitWidth &width, const char *unitDisplayCase, const PluralRules *rules, const MicroPropsGenerator *parent, UErrorCode &status) { LocalPointer<LongNameMultiplexer> result(new LongNameMultiplexer(parent), status); if (U_FAILURE(status)) { return nullptr; } U_ASSERT(units.length() > 0); if (result->fHandlers.resize(units.length()) == nullptr) { status = U_MEMORY_ALLOCATION_ERROR; return nullptr; } result->fMeasureUnits.adoptInstead(new MeasureUnit[units.length()]); for (int32_t i = 0, length = units.length(); i < length; i++) { const MeasureUnit &unit = *units[i]; result->fMeasureUnits[i] = unit; if (unit.getComplexity(status) == UMEASURE_UNIT_MIXED) { MixedUnitLongNameHandler *mlnh = result->fMixedUnitHandlers.createAndCheckErrorCode(status); MixedUnitLongNameHandler::forMeasureUnit(loc, unit, width, unitDisplayCase, rules, NULL, mlnh, status); result->fHandlers[i] = mlnh; } else { LongNameHandler *lnh = result->fLongNameHandlers.createAndCheckErrorCode(status); LongNameHandler::forMeasureUnit(loc, unit, width, unitDisplayCase, rules, NULL, lnh, status); result->fHandlers[i] = lnh; } if (U_FAILURE(status)) { return nullptr; } } return result.orphan(); } void LongNameMultiplexer::processQuantity(DecimalQuantity &quantity, MicroProps &micros, UErrorCode &status) const { // We call parent->processQuantity() from the Multiplexer, instead of // letting LongNameHandler handle it: we don't know which LongNameHandler to // call until we've called the parent! fParent->processQuantity(quantity, micros, status); // Call the correct LongNameHandler based on outputUnit for (int i = 0; i < fHandlers.getCapacity(); i++) { if (fMeasureUnits[i] == micros.outputUnit) { fHandlers[i]->processQuantity(quantity, micros, status); return; } } if (U_FAILURE(status)) { return; } // We shouldn't receive any outputUnit for which we haven't already got a // LongNameHandler: status = U_INTERNAL_PROGRAM_ERROR; } #endif /* #if !UCONFIG_NO_FORMATTING */
; ----------------------------- SFMT64.ASM --------------------------- ; Author: Agner Fog ; Date created: 2008-11-01 ; Last modified: 2013-12-15 ; Project: randoma library of random number generators ; Source URL: www.agner.org/random ; Description: ; Random number generator of type SIMD-oriented Fast Mersenne Twister (SFMT) ; (Mutsuo Saito and Makoto Matsumoto: "SIMD-oriented Fast Mersenne Twister: ; a 128-bit Pseudorandom Number Generator", Monte Carlo and Quasi-Monte ; Carlo Methods 2006, Springer, 2008, pp. 607-622). ; ; 64-bit mode version for x86-64 compatible microprocessors. ; Copyright (c) 2008-2013 GNU General Public License www.gnu.org/licenses ; ---------------------------------------------------------------------- default rel global SFMTRandomInit, SFMTRandomInitByArray, SFMTBRandom, SFMTRandom global SFMTRandomL, SFMTIRandom, SFMTIRandomX, SFMTgenRandomInit global SFMTgenRandomInitByArray, SFMTgenRandom, SFMTgenRandomL, SFMTgenIRandom global SFMTgenIRandomX, SFMTgenBRandom %IFDEF WINDOWS global SFMTgenRandomInitD, SFMTgenRandomInitByArrayD, SFMTgenIRandomD global SFMTgenIRandomXD, SFMTgenRandomD, SFMTgenBRandomD %ENDIF extern InstructionSet ; structure definition and constants: %INCLUDE "../randomah.asi" section .data align 16 ; Data for single instance of random number generator SFMTInstance: ISTRUC CRandomSFMTA ; Size of structure IEND SFMTSize equ $-SFMTInstance align 16 ; Initialization constants for Mother-Of-All: InitMother DD 2111111111, 0, 1492, 0, 1776, 0, 5115, 0 ; Initialization Mask for SFMT: InitMask DD SFMT_MASK ; Period certification vector for SFMT: InitParity DD SFMT_PARITY SECTION .CODE align=16 ; code segment ; --------------------------------------------------------------- ; Thread-safe static link versions for SFMT ; --------------------------------------------------------------- ; extern "C" void SFMTRandomInit(void * Pthis, int ThisSize, int seed, int IncludeMother = 0); ; Parameters: ; par1 = Pthis ; par2d = ThisSize ; par3d = seed ; par4d = IncludeMother SFMTRandomInit: cmp par2d, SFMTSize jb Error ; Error exit if buffer too small push rbx ; Align by 16. Will overlap part of Fill if Pthis unaligned and par1, -16 xor eax, eax test par4d, par4d ; IncludeMother setnz al ; convert any nonzero value to 1 ; Store USEMOTHER mov [par1+CRandomSFMTA.USEMOTHER], eax mov eax, par3d ; seed xor ebx, ebx ; loop counter i jmp L002 ; go into seeding loop L001: ; seeding loop for SFMT ; y = factor * (y ^ (y >> 30)) + (++i); call InitSubf0 ; randomization subfunction L002: mov [par1+rbx*4+CRandomSFMTA.STATE],eax ; initialize state cmp ebx, SFMT_N*4 - 1 jb L001 ; Put 5 more values into Mother-Of-All generator call InitSubf0 mov [par1+CRandomSFMTA.M0], eax call InitSubf0 mov [par1+CRandomSFMTA.M1], eax call InitSubf0 mov [par1+CRandomSFMTA.M2], eax call InitSubf0 mov [par1+CRandomSFMTA.M3], eax call InitSubf0 mov [par1+CRandomSFMTA.MC], eax ; more initialization and period certification call InitAndPeriod pop rbx ret ;SFMTRandomInit ENDP Error: ; Error exit xor eax, eax div eax ; Divide by 0 ret ; Subfunction used by SFMTRandomInit InitSubf0: ; private ; y = 1812433253 * (y ^ (y >> 30)) + (++i); ; input parameters: ; eax = y ; ebx = i ; output: ; eax = new y ; ebx = i+1 ; edx modified mov edx, eax shr eax, 30 xor eax, edx imul eax, 1812433253 inc ebx add eax, ebx ret ;InitSubf0 endp ; Subfunction used by SFMTRandomInitByArray InitSubf1: ; private ; r = 1664525U * (r ^ (r >> 27)); ; input parameters: ; eax = r ; output: ; eax = new r ; r10 modified mov r10d, eax shr eax, 27 xor eax, r10d imul eax, 1664525 ret ;InitSubf1 endp ; Subfunction used by SFMTRandomInitByArray InitSubf2: ; private ; r = 1566083941U * (r ^ (r >> 27)); ; input parameters: ; eax = r ; output: ; eax = new r ; r10 modified mov r10d, eax shr eax, 27 xor eax, r10d imul eax, 1566083941 ret ;InitSubf2 endp ; Subfunciton for initialization and period certification, except seeding ; par1 = aligned pointer to CRandomSFMTA InitAndPeriod: ; private push rbx ; initialize constants for Mother-Of-All movaps xmm0, oword [InitMother] movaps oword [par1+CRandomSFMTA.MF3], xmm0 movaps xmm0, oword [InitMother+16] movaps oword [par1+CRandomSFMTA.MF1], xmm0 ; initialize constants for SFMT movaps xmm0, oword [InitMask] movaps oword [par1+CRandomSFMTA.AMASK], xmm0 ; initialize various variables xor eax, eax mov dword [par1+CRandomSFMTA.one], eax mov dword [par1+4+CRandomSFMTA.one], 3FF00000H mov dword [par1+CRandomSFMTA.LASTINTERVAL], eax ; get instruction set push par1 call InstructionSet pop par1 mov [par1+CRandomSFMTA.Instset], eax ; Period certification ; Compute parity of STATE[0-4] & InitParity movaps xmm1, oword [par1+CRandomSFMTA.STATE] andps xmm1, oword [InitParity] movhlps xmm2, xmm1 ; high qword xorps xmm1, xmm2 ; xor two qwords pshufd xmm2, xmm1, 1 ; high dword xorps xmm1, xmm2 ; xor two dwords movd eax, xmm1 ; do rest of xor in eax mov edx, eax shr eax, 16 xor eax, edx ; xor two words xor al, ah ; xor two bytes jpo L008 ; parity odd: period OK ; parity even: period not OK ; Find a nonzero dword in period certification vector xor ebx, ebx ; loop counter lea rdx, [InitParity] L005: mov eax, [rdx+rbx*4] ; InitParity[i] test eax, eax jnz L006 inc ebx ; assume that there is a nonzero dword in InitParity jmp L005 ; loop until nonzero found L006: ; find first nonzero bit in eax bsf edx, eax ; flip the corresponding bit in STATE btc [par1+rbx*4+CRandomSFMTA.STATE], edx L008: cmp dword [par1+CRandomSFMTA.USEMOTHER], 0 je L009 call Mother_Next ; Make first random number ready L009: ; Generate first random numbers and set IX = 0 call SFMT_Generate pop rbx ret ;InitAndPeriod endp ; extern "C" void SFMTRandomInitByArray ; (void * Pthis, int ThisSize, int const seeds[], int NumSeeds, int IncludeMother = 0); ; // Seed by more than 32 bits SFMTRandomInitByArray: ; Parameters ; par1 = Pthis ; par2d = ThisSize ; par3 = seeds ; par4d = NumSeeds ; par5d = IncludeMother ; define constants: SFMT_SIZE equ SFMT_N*4 ; number of 32-bit integers in state %IF SFMT_SIZE >= 623 SFMT_LAG equ 11 %ELIF SFMT_SIZE >= 68 SFMT_LAG equ 7 %ELIF SFMT_SIZE >= 39 SFMT_LAG equ 5 %ELSE SFMT_LAG equ 3 %ENDIF SFMT_MID equ ((SFMT_SIZE - SFMT_LAG) / 2) xor eax, eax cmp par5d, eax ; IncludeMother (parameter is on stack if windows) setnz al ; convert any nonzero value to 1 push rbx push rbp cmp par2d, SFMTSize ; ThisSize jb Error ; Error exit if buffer too small ; Align by 16. Will overlap part of Fill if Pthis unaligned and par1, -16 ; Store USEMOTHER mov [par1+CRandomSFMTA.USEMOTHER], eax ; 1. loop: Fill state vector with random numbers from NumSeeds ; r = NumSeeds; ; for (i = 0; i < SFMT_N*4; i++) { ; r = factor * (r ^ (r >> 30)) + i; ; sta[i] = r;} mov eax, par4d ; r = NumSeeds xor ebx, ebx ; i L100: mov par2d, eax shr eax, 30 xor eax, par2d imul eax, 1812433253 add eax, ebx mov [par1+rbx*4+CRandomSFMTA.STATE], eax inc ebx cmp ebx, SFMT_SIZE jb L100 ; count = max(NumSeeds,size-1) mov eax, SFMT_SIZE - 1 mov r11d, par4d ; NumSeeds cmp r11d, eax cmovb r11d, eax ; 2. loop: Fill state vector with random numbers from seeds[] ; for (i = 1, j = 0; j < count; j++) { ; r = func1(sta[i] ^ sta[(i + mid) % size] ^ sta[(i + size - 1) % size]); ; sta[(i + mid) % size] += r; ; if (j < NumSeeds) r += seeds[j] ; r += i; ; sta[(i + mid + lag) % size] += r; ; sta[i] = r; ; i = (i + 1) % size; ; } ; register use: ; par1 = Pthis ; par2 = j ; par3 = seeds ; par4 = NumSeeds ; eax = r ; ebx = i ; ebp = (i + mid) % size, (i + mid + lag) % size ; r10 = (i + size - 1) % size ; r11 = count xor par2d, par2d ; j = 0 lea ebx, [par2+1] ; i = 1 L101: ; r = sta[i] ^ sta[(i + mid) % size] ^ sta[(i + size - 1) % size]; mov eax, [par1+rbx*4+CRandomSFMTA.STATE] ; sta[i] lea ebp, [rbx+SFMT_MID] cmp ebp, SFMT_SIZE jb L102 sub ebp, SFMT_SIZE L102: xor eax, [par1+rbp*4+CRandomSFMTA.STATE] ; sta[(i + mid) % size] lea r10d, [rbx+SFMT_SIZE-1] cmp r10d, SFMT_SIZE jb L103 sub r10d, SFMT_SIZE L103: xor eax, [par1+r10*4+CRandomSFMTA.STATE] ; sta[(i + size - 1) % size] ; r = func1(r) = (r ^ (r >> 27)) * 1664525U; call InitSubf1 ; sta[(i + mid) % size] += r; add [par1+rbp*4+CRandomSFMTA.STATE], eax ; if (j < NumSeeds) r += seeds[j] cmp par2d, par4d jnb L104 add eax, [par3+par2*4] L104: ; r += i; add eax, ebx ; sta[(i + mid + lag) % size] += r; lea ebp, [rbx+SFMT_MID+SFMT_LAG] cmp ebp, SFMT_SIZE jb L105 sub ebp, SFMT_SIZE L105: add [par1+rbp*4+CRandomSFMTA.STATE], eax ;sta[i] = r; mov [par1+rbx*4+CRandomSFMTA.STATE], eax ; i = (i + 1) % size; inc ebx cmp ebx, SFMT_SIZE jb L106 sub ebx, SFMT_SIZE L106: ; j++, loop while j < count inc par2d cmp par2d, r11d jb L101 ; 3. loop: Randomize some more ; for (j = 0; j < size; j++) { ; r = func2(sta[i] + sta[(i + mid) % size] + sta[(i + size - 1) % size]); ; sta[(i + mid) % size] ^= r; ; r -= i; ; sta[(i + mid + lag) % size] ^= r; ; sta[i] = r; ; i = (i + 1) % size; ; } ; j = 0 xor par2d, par2d L110: ; r = sta[i] + sta[(i + mid) % size] + sta[(i + size - 1) % size] mov eax, [par1+rbx*4+CRandomSFMTA.STATE] ; sta[i] lea ebp, [rbx+SFMT_MID] cmp ebp, SFMT_SIZE jb L111 sub ebp, SFMT_SIZE L111: add eax, [par1+rbp*4+CRandomSFMTA.STATE] ; sta[(i + mid) % size] lea r10d, [rbx+SFMT_SIZE-1] cmp r10d, SFMT_SIZE jb L112 sub r10d, SFMT_SIZE L112: add eax, [par1+r10*4+CRandomSFMTA.STATE] ; sta[(i + size - 1) % size] ; r = func2(r) = (x ^ (x >> 27)) * 1566083941U; call InitSubf2 ; sta[(i + mid) % size] ^= r; xor [par1+rbp*4+CRandomSFMTA.STATE], eax ; r -= i; sub eax, ebx ; sta[(i + mid + lag) % size] ^= r; lea ebp, [rbx+SFMT_MID+SFMT_LAG] cmp ebp, SFMT_SIZE jb L113 sub ebp, SFMT_SIZE L113: xor [par1+rbp*4+CRandomSFMTA.STATE], eax ; sta[i] = r; mov [par1+rbx*4+CRandomSFMTA.STATE], eax ; i = (i + 1) % size; inc ebx cmp ebx, SFMT_SIZE jb L114 sub ebx, SFMT_SIZE L114: ; j++, loop while j < size inc par2d cmp par2d, SFMT_SIZE jb L110 ; if (UseMother) { cmp dword [par1+CRandomSFMTA.USEMOTHER], 0 jz L120 ; 4. loop: Initialize MotherState ; for (j = 0; j < 5; j++) { ; r = func2(r) + j; ; MotherState[j] = r + sta[2*j]; ; } call InitSubf2 mov par2d, [par1+CRandomSFMTA.STATE] add par2d, eax mov [par1+CRandomSFMTA.M0], par2d call InitSubf2 inc eax mov par2d, [par1+8+CRandomSFMTA.STATE] add par2d, eax mov [par1+CRandomSFMTA.M1], par2d call InitSubf2 add eax, 2 mov par2d, [par1+16+CRandomSFMTA.STATE] add par2d, eax mov [par1+CRandomSFMTA.M2], par2d call InitSubf2 add eax, 3 mov par2d, [par1+24+CRandomSFMTA.STATE] add par2d, eax mov [par1+CRandomSFMTA.M3], par2d call InitSubf2 add eax, 4 mov par2d, [par1+32+CRandomSFMTA.STATE] add par2d, eax mov [par1+CRandomSFMTA.MC], par2d L120: ; More initialization and period certification call InitAndPeriod pop rbp pop rbx ret ;SFMTRandomInitByArray ENDP Mother_Next: ; private ; Internal procedure: advance Mother-Of-All generator ; The random value is in M0 ; par1 = aligned pointer to structure CRandomSFMTA ; eax, par1, xmm0 unchanged movdqa xmm1, oword [par1+CRandomSFMTA.M3] ; load M3,M2 movdqa xmm2, oword [par1+CRandomSFMTA.M1] ; load M1,M0 movhps qword [par1+CRandomSFMTA.M3], xmm1 ; M3=M2 movq qword [par1+CRandomSFMTA.M2], xmm2 ; M2=M1 movhps qword [par1+CRandomSFMTA.M1], xmm2 ; M1=M0 pmuludq xmm1, oword [par1+CRandomSFMTA.MF3] ; M3*MF3, M2*MF2 pmuludq xmm2, oword [par1+CRandomSFMTA.MF1] ; M1*MF1, M0*MF0 paddq xmm1, xmm2 ; P3+P1, P2+P0 movhlps xmm2, xmm1 ; Get high qword movq xmm3, qword [par1+CRandomSFMTA.MC] ; +carry paddq xmm1, xmm3 paddq xmm1, xmm2 ; P0+P1+P2+P3 movq qword [par1+CRandomSFMTA.M0], xmm1 ; Store new M0 and carry ret ;Mother_Next endp align 16 SFMT_Generate: ; private ; void CRandomSFMT::Generate() { ; Fill state array with new random numbers push rbx ; register use ; par1 = Pthis (rcx or rdi) ; edx = i*16 + offset state ; eax, ebx = loop end ; xmm1 = r1 ; xmm2 = r2 = r ; xmm0, xmm3 = scratch ; r1 = state[SFMT_N*16 - 2]; ; r2 = state[SFMT_N*16 - 1]; movdqa xmm1, oword [par1+(SFMT_N-2)*16+CRandomSFMTA.STATE] movdqa xmm2, oword [par1+(SFMT_N-1)*16+CRandomSFMTA.STATE] mov edx, CRandomSFMTA.STATE ;static inline __m128i sfmt_recursion(__m128i const &a, __m128i const &b, ;__m128i const &c, __m128i const &d, __m128i const &mask) { ; __m128i a1, b1, c1, d1, z1, z2; ; b1 = _mm_srli_epi32(b, SFMT_SR1); ; a1 = _mm_slli_si128(a, SFMT_SL2); ; c1 = _mm_srli_si128(c, SFMT_SR2); ; d1 = _mm_slli_epi32(d, SFMT_SL1); ; b1 = _mm_and_si128(b1, mask); ; z1 = _mm_xor_si128(a, a1); ; z2 = _mm_xor_si128(b1, d1); ; z1 = _mm_xor_si128(z1, c1); ; z2 = _mm_xor_si128(z1, z2); ; return z2;} ; for (i = 0; i < SFMT_N - SFMT_M; i++) { ; r = sfmt_recursion(state[i], state[i + SFMT_M], r1, r2, mask); ; state[i] = r; ; r1 = r2; ; r2 = r; ; } mov eax, (SFMT_N-SFMT_M)*16 + CRandomSFMTA.STATE ; first loop end mov ebx, SFMT_N*16 + CRandomSFMTA.STATE ; second loop end ; first i loop from 0 to SFMT_N - SFMT_M align 8 L201: movdqa xmm0, oword [par1+rdx+SFMT_M*16] ; b psrld xmm0, SFMT_SR1 ; b1 pand xmm0, oword [par1+CRandomSFMTA.AMASK] ; b1 movdqa xmm3, oword [par1+rdx] ; a pxor xmm0, xmm3 pslldq xmm3, SFMT_SL2 ; a1 psrldq xmm1, SFMT_SR2 ; c1, c = r1 pxor xmm0, xmm3 pxor xmm0, xmm1 movdqa xmm1, xmm2 ; r1 = r2 pslld xmm2, SFMT_SL1 ; d1, d = r2 pxor xmm2, xmm0 ; r2 = r ; state[i] = r; movdqa oword [par1+rdx], xmm2 ; i++ while i < SFMT_N - SFMT_M add edx, 16 cmp edx, eax jb L201 ;align 16 L202: ; second i loop from SFMT_N - SFMT_M + 1 to SFMT_N movdqa xmm0, oword [par1+rdx+(SFMT_M-SFMT_N)*16]; b psrld xmm0, SFMT_SR1 ; b1 pand xmm0, oword [par1+CRandomSFMTA.AMASK] ; b1 movdqa xmm3, oword [par1+rdx] ; a pxor xmm0, xmm3 pslldq xmm3, SFMT_SL2 ; a1 psrldq xmm1, SFMT_SR2 ; c1, c = r1 pxor xmm0, xmm3 pxor xmm0, xmm1 movdqa xmm1, xmm2 ; r1 = r2 pslld xmm2, SFMT_SL1 ; d1, d = r2 pxor xmm2, xmm0 ; r2 = r ; state[i] = r; movdqa oword [par1+rdx], xmm2 ; i++ while i < SFMT_N add edx, 16 cmp edx, ebx jb L202 ; Check if initialized L208: cmp dword [par1+CRandomSFMTA.AMASK], SFMT_MASK1 jne Error ; Make error if not initialized ; ix = 0; mov dword [par1+CRandomSFMTA.IX], 0 ; point to start of STATE buffer pop rbx ret ;SFMT_Generate endp ; extern "C" unsigned int SFMTBRandom(void * Pthis); // Output random bits SFMTBRandom: ; generate random bits ; Align Pthis by 16. Will overlap part of Fill1 if Pthis unaligned and par1, -16 SFMTBRandom_reg: ; Entry for register parameters, used internally ; if (ix >= SFMT_N*4) Generate(); mov edx, [par1+CRandomSFMTA.IX] cmp edx, SFMT_N*16 jnb NeedGenerate ; y = ((uint32_t*)state)[ix++]; mov eax, dword [par1+rdx+CRandomSFMTA.STATE] add edx, 4 mov [par1+CRandomSFMTA.IX], edx AfterGenerate: ; if (UseMother) y += MotherBits(); cmp dword [par1+CRandomSFMTA.USEMOTHER], 0 jz NoMother ; add mother bits add eax, [par1+CRandomSFMTA.M0] ; Add Mother random number call Mother_Next ; Make next Mother random number ready NoMother: ; return y; ret NeedGenerate: call SFMT_Generate ; generate SFMT_N*4 random dwords mov eax, [par1+CRandomSFMTA.STATE] mov dword [par1+CRandomSFMTA.IX], 4 jmp AfterGenerate ;SFMTBRandom ENDP ; extern "C" double SFMTRandom (void * Pthis); // Output random float SFMTRandom: ; generate random float with 52 bits resolution ; Align Pthis by 16. Will overlap part of Fill1 if Pthis unaligned and par1, -16 SFMTRandom_reg: ; internal entry point ; check if there are at least 64 random bits in state buffer ; if (ix >= SFMT_N*4-1) Generate(); mov edx, [par1+CRandomSFMTA.IX] cmp edx, SFMT_N*16-4 jnb L303 L301: ; read 64 random bits movq xmm0, qword [par1+rdx+CRandomSFMTA.STATE] add edx, 8 mov [par1+CRandomSFMTA.IX], edx ; combine with Mother-Of-All generator? cmp dword [par1+CRandomSFMTA.USEMOTHER], 0 jz L302 ; ConvertToFloat ; add mother bits movq xmm1, qword [par1+CRandomSFMTA.M0] ; Mother random number MC and M0 pshuflw xmm1, xmm1, 01001011B ; Put M0 before MC, and swap the words in MC paddq xmm0, xmm1 ; Add SFMT and Mother outputs call Mother_Next ; Make next Mother random number ready L302: ; ConvertToFloat psrlq xmm0, 12 ; align with mantissa field of double precision float movsd xmm1, [par1+CRandomSFMTA.one] ; 1.0 double precision por xmm0, xmm1 ; insert exponent to get 1.0 <= x < 2.0 subsd xmm0, xmm1 ; subtract 1.0 to get 0.0 <= x < 1.0 ret ; return value L303: ; NeedGenerateR call SFMT_Generate ; generate SFMT_N*4 random dwords xor edx, edx jmp L301 ;SFMTRandom ENDP ; extern "C" long double SFMTRandomL (void * Pthis); SFMTRandomL: ; generate random float with 63 bits resolution ; Align Pthis by 16. and par1, -16 SFMTRandomL_reg: ; internal entry point ; check if there are at least 64 random bits in state buffer ; if (ix >= SFMT_N*4-1) Generate(); mov edx, [par1+CRandomSFMTA.IX] cmp edx, SFMT_N*16-4 jnb L403 L401: ; read 64 random bits movq xmm0, qword [par1+rdx+CRandomSFMTA.STATE] add edx, 8 mov [par1+CRandomSFMTA.IX], edx ; combine with Mother-Of-All generator? cmp dword [par1+CRandomSFMTA.USEMOTHER], 0 jz L402 ; add mother bits movq xmm1, qword [par1+CRandomSFMTA.M0] ; Mother random number MC and M0 pshuflw xmm1, xmm1, 01001011B ; Put M0 before MC, and swap the words in MC paddq xmm0, xmm1 ; Add SFMT and Mother outputs call Mother_Next ; Make next Mother random number ready L402: ;ConvertToFloat sub rsp, 16 ; make space for long double psrlq xmm0, 1 ; align with mantissa field of long double pcmpeqw xmm1, xmm1 ; all 1's psllq xmm1, 63 ; create a 1 in bit 63 por xmm0, xmm1 ; bit 63 is always 1 in long double movq qword [rsp], xmm0 ; store mantissa mov dword [rsp+8], 3FFFH ; exponent fld tword [rsp] ; load long double fsub qword [par1+CRandomSFMTA.one] ; subtract 1.0 to get 0.0 <= x < 1.0 pcmpeqw xmm0, xmm0 ; make a NAN for compilers that don't support long double add rsp, 16 ret ; return value in st(0) L403: ;NeedGenerateR call SFMT_Generate ; generate SFMT_N*4 random dwords xor edx, edx jmp L401 ;SFMTRandomL ENDP ; extern "C" int SFMTIRandom (void * Pthis, int min, int max); // Output random integer SFMTIRandom: ; par1 = Pthis ; par2d = min ; par3d = max ; Align Pthis by 16. and par1, -16 push par2 ; save min, max push par3 call SFMTBRandom_reg ; random bits pop rdx ; max pop rcx ; min sub edx, ecx jl short WrongInterval ; max < min inc edx ; max - min + 1 mul edx ; multiply random number by interval and truncate lea eax, [rdx+rcx] ; add min to high dword of product ret WrongInterval: mov eax, 80000000H ; error exit ret ;SFMTIRandom ENDP ; extern "C" int SFMTIRandomX (void * Pthis, int min, int max); // Output random integer SFMTIRandomX: ; par1 = Pthis ; par2d = min ; par3d = max push rbx ; Align Pthis by 16. and par1, -16 mov ebx, par3d sub ebx, par2d ; max - min jle short M30 ; max <= min (signed) inc ebx ; interval = max - min + 1 ; if (interval != LastInterval) { cmp ebx, [par1+CRandomSFMTA.LASTINTERVAL] je M10 ; need to calculate new rejection limit ; RLimit = uint32(((uint64)1 << 32) / interval) * interval - 1;} xor eax, eax ; 0 lea edx, [eax+1] ; 1 div ebx ; (would give overflow if interval = 1) mul ebx dec eax mov [par1+CRandomSFMTA.RLIMIT], eax mov [par1+CRandomSFMTA.LASTINTERVAL], ebx M10: mov ebx, par2d ; save min M20: ; do { // Rejection loop call SFMTBRandom_reg ; random bits (par1 is preserved) ; longran = (uint64)BRandom() * interval; mul dword [par1+CRandomSFMTA.LASTINTERVAL] ; } while (remainder > RLimit); cmp eax, [par1+CRandomSFMTA.RLIMIT] ja M20 ; return (int32)iran + min lea eax, [rbx+rdx] pop rbx ret M30: jl M40 ; max = min. Return min mov eax, par2d pop rbx ret ; max = min exit M40: ; max < min: error mov eax, 80000000H ; error exit pop rbx ret ;SFMTIRandomX ENDP ; ------------------------------------------------------------------------- ; Single-threaded static link versions for SFMT generator ; ------------------------------------------------------------------------- ; extern "C" void SFMTgenRandomInit(int seed, int IncludeMother = 0); SFMTgenRandomInit: %IFDEF WINDOWS SFMTgenRandomInitD: %ENDIF ; par1d = seed ; par2d = IncludeMother ; set up parameters for call SFMTRandomInit mov par4d, par2d ; IncludeMother mov par3d, par1d ; seed mov par2d, SFMTSize ; ThisSize lea par1, [SFMTInstance] ; Get address of SFMTInstance into par1 jmp SFMTRandomInit ;SFMTgenRandomInit ENDP ; extern "C" void SFMTgenRandomInitByArray(int const seeds[], int NumSeeds, int IncludeMother = 0); SFMTgenRandomInitByArray: ; par1 = seeds ; par2d = NumSeeds ; par3d = IncludeMother ; set up parameters for call SFMTRandomInitByArray %IFDEF WINDOWS SFMTgenRandomInitByArrayD: push par3 ; IncludeMother on stack sub rsp, 32 ; empty shadow space mov par4d, par2d ; NumSeeds mov par3, par1 ; seeds mov par2d, SFMTSize ; ThisSize lea par1, [SFMTInstance] ; Get address of SFMTInstance into par1 call SFMTRandomInitByArray add rsp, 40 ret %ELSE ; UNIX mov par5d, par3d ; IncludeMother in register mov par4d, par2d ; NumSeeds mov par3, par1 ; seeds mov par2d, SFMTSize ; ThisSize lea par1, [SFMTInstance] ; Get address of SFMTInstance into par1 jmp SFMTRandomInitByArray %ENDIF ;SFMTgenRandomInitByArray ENDP ; extern "C" double SFMTgenRandom(); SFMTgenRandom: ; generate random float with 52 bits resolution %IFDEF WINDOWS SFMTgenRandomD: %ENDIF lea par1, [SFMTInstance] ; Get address of SFMTInstance into par1 jmp SFMTRandom_reg ; random bits ;SFMTgenRandom ENDP ; extern "C" double SFMTgenRandom(); SFMTgenRandomL: ; generate random float with 63 bits resolution lea par1, [SFMTInstance] ; Get address of SFMTInstance into par1 jmp SFMTRandomL_reg ; random bits ;SFMTgenRandomL ENDP ; extern "C" int SFMTgenIRandom (int min, int max); SFMTgenIRandom: %IFDEF WINDOWS SFMTgenIRandomD: %ENDIF mov par3d, par2d mov par2d, par1d lea par1, [SFMTInstance] ; Get address of SFMTInstance into par1 jmp SFMTIRandom ; continue in _SFMTIRandom ;SFMTgenIRandom ENDP ; extern "C" int SFMTgenIRandomX (int min, int max); SFMTgenIRandomX: %IFDEF WINDOWS SFMTgenIRandomXD: %ENDIF mov par3d, par2d mov par2d, par1d lea par1, [SFMTInstance] ; Get address of SFMTInstance into par1 jmp SFMTIRandomX ; continue in _SFMTIRandomX ;SFMTgenIRandomX ENDP ; extern "C" uint32_t SFMTgenBRandom(); SFMTgenBRandom: ; generate random float with 32 bits resolution %IFDEF WINDOWS SFMTgenBRandomD: %ENDIF lea par1, [SFMTInstance] ; Get address of SFMTInstance into par1 jmp SFMTBRandom_reg ; random bits ;SFMTgenBRandom ENDP ;END
<% from pwnlib.shellcraft.aarch64.linux import syscall %> <%page args="resource, rlimits"/> <%docstring> Invokes the syscall getrlimit. See 'man 2 getrlimit' for more information. Arguments: resource(rlimit_resource_t): resource rlimits(rlimit): rlimits </%docstring> ${syscall('SYS_getrlimit', resource, rlimits)}
/* * Copyright 2018 Jan Tschada * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "pch.h" #include "Random.h" #include <stdlib.h> #include <time.h> using namespace std; using namespace std::chrono; namespace model { Random::Random() { srand(time(nullptr)); } Random::~Random() { } double Random::nextDouble() { return (double)(rand()/(double)RAND_MAX); } }
CPU 8086 %define VIDEOBIOS 0x10 %define SETVIDEOMODE 0 %define CGA6 0x06 %define WIDTHPX 160d %define HEIGHTPX 100d %define PXB 2 ; Pixeles por byte %assign BYTESPERSCAN (WIDTHPX / PXB) %define MEMCGAEVEN 0xB800 %define MEMCGAODD 0xBA00 %define KB_ESC 01 %define KB_UP 48h %define KB_DOWN 50h %define KB_LEFT 4Bh %define KB_RIGHT 4Dh ; Constantes del juego %define GRAVEDAD 1 %define REBOTEY 10 %define ANCHOSPRITE 16 %define ALTOSPRITE 16 %define BWSPRITE ( ANCHOSPRITE / PXB ) ; Ancho de Sprite en Bytes ; Macros ; vsync: Esperar retrazo vertical %macro VSync 0 MOV DX, 03DAH %%Retrace1: IN AL,DX ; AL := Port[03DAH] TEST AL,8 ; Is bit 3 set? JZ %%Retrace1 ; No, continue waiting %%Retrace2: ; IN AL,DX IN AL,DX ; AL := Port[03DAH] TEST AL,8 ; Is bit 3 unset? JNZ %%Retrace2 ; No, continue waiting %endmacro org 100h section .text start: ; 1 .- Guardar Rutina de interrupcion del teclado del sistema (BIOS) mov al,9h mov ah,35h int 21h mov [kb_int_old_off], bx mov [kb_int_old_seg], es ; 2 .- Registrar nueva rutina de interrupción del teclado mov al, 9h mov ah, 25h mov bx, cs mov ds, bx mov dx, kb_int_new int 21h ; 3 .- Establecer modo de video mov ah, SETVIDEOMODE ; Establecer modo de video mov al, CGA6 ; CGA Modo 6: monocromatico hi-res o composite lo-res int VIDEOBIOS ; LLamar a la BIOS para servicios de video ; 3.1 .- Entrar en modo de video compuesto mov dx, 03D8h mov al, 00011010b out dx, al ; 4 .- Dibujar sprite en su posicion inicial mov ax, [spritey] mov bx, [spritex] mov dx, spritemonigote call dibujasprite16 frame: ; 1 .- Llamar a 'mecanicadeljuego' para que calcule posicion de sprites call mecanicadeljuego ; 2 .- VSync VSync ; 3 .- borrar mov ax, [spritey] mov bx, [spritex] call borrasprite16 ; 4.- dibujar mov ax, [spriteny] mov bx, [spritenx] mov [spritey], ax mov [spritex], bx mov dx, spritemonigote call dibujasprite16 ; repetir ciclo jmp frame leerteclado_old: ; 1.- Revisar teclado mov ah, 1 ; "Get keystroke status" int 16h jz .retorno mov ah, 0 ; Problema: Por alguna razon tengo que hacer lectura destructiva de teclado para que reporte la tecla presionada int 16h cmp ah, KB_ESC ; Comprobar si es tecla ESC je fin cmp al, 'q' ; Comprobar si es caracter 'q' je fin cmp al, 'Q' ; Comprobar si es caracter 'Q' je fin cmp al, 'p' ; Comprobar si es caracter 'p' je cambiapaleta cmp al, 'P' ; Comprobar si es caracter 'P' je cambiapaleta cmp ah, KB_LEFT ; Comprobar si es flecha izquierda je .movizq cmp ah, KB_RIGHT ; Comprobar si es flecha derecha je .movder cmp ah, KB_UP ; Comprobar si es flecha arriba je .saltar .retorno: ret .movizq: mov ax, -1 mov [deltax], ax ret .movder: mov ax, 1 mov [deltax], ax ret .saltar: mov ax, [parado] ; Tiene que estar parado para poder saltar test ax, ax jz .noparado mov bx, 0 - REBOTEY mov [deltay], bx mov bx, 0 mov [parado], bx .noparado: ret leerteclado: mov al, [tecla_esc] ; ¿está presionada esta tecla? test al, al jnz fin mov al, [tecla_left] ; ¿está presionada esta tecla? test al, al jz .sig1 .movizq: mov ax, [deltax] dec ax dec ax mov [deltax], ax .sig1: mov al, [tecla_right] ; ¿está presionada esta tecla? test al, al jz .sig2 .movder: mov ax, [deltax] inc ax inc ax mov [deltax], ax .sig2: mov al, [tecla_up] ; ¿está presionada esta tecla? test al, al jz .sig3 .saltar: mov ax, [parado] ; Tiene que estar parado para poder saltar test ax, ax jz .noparado mov bx, 0 - REBOTEY mov [deltay], bx mov bx, 0 mov [parado], bx .noparado: .sig3: .retorno: ret kb_int_new: ; Keyboard Interrupt Handler sti ; ??? ¿habilitar interrupciones? ; Guardar registros push ax push bx push cx push dx push si push di push ds push es mov ax, cs ; Usar segemtno actual del programa, basado en cs mov ds, ax mov es, ax in al, 60h ; obtener scancode mov bl, al ; respaldarlo en otro registro in al, 61h mov ah, al ;Save keyboard status or al, 80h ;Disable out 61h, al mov al, ah ;Enable (If it was disabled at first, you wouldn't out 61h, al ; be doing this anyway :-) xchg ax, bx ; Revisar si es tecla presionada o liberada test al, 80h ; Codigo de tecla liberada jnz .k_liberada .k_presionada: mov ah, 1 ; Valor 1 para tecla presionada jmp .cualtecla .k_liberada: and al, 7fh ; Conservar scancode de tecla, desechando bit de presionada o liberada mov ah, 0 ; valor 0 para tecla liberada .cualtecla: cmp al, KB_ESC jne .sig1 mov bx, tecla_esc jmp .guardar .sig1: cmp al, KB_LEFT jne .sig2 mov bx, tecla_left jmp .guardar .sig2: cmp al, KB_RIGHT jne .sig3 mov bx, tecla_right jmp .guardar .sig3: cmp al, KB_UP jne .sig4 mov bx, tecla_up jmp .guardar .sig4: jmp .salida .guardar: ;mov di, bx mov byte [bx], ah ; Almacenar valor 1 ó 0 en registro de tecla correspondiente .salida: ;mov byte [tecla_esc], 11b cli ; ??? ¿Deshabilitar interrupciones ; Enviar señal EOI (End of Interrupt) mov al,20h out 20h,al ; reestablecer registros pop es pop ds pop di pop si pop dx pop cx pop bx pop ax iret cambiapaleta: mov ah, [paleta] test ah, ah jz .sig mov bl, 0 jmp .guarda .sig: mov bl, 1 .guarda: mov [paleta], bl .llama_a_bios: mov ah, 0Bx ; Establecer paleta de colores mov bh, 1 ; Paleta de cuatro colores mov bl, [paleta] int VIDEOBIOS ret mecanicadeljuego: mov ax, [deltax] cmp ax, 0 je .leetec jg .decdx inc ax mov [deltax], ax jmp .leetec .decdx: dec ax mov [deltax], ax ; 1.- Leer el teclado .leetec: call leerteclado mov ax, [deltax] cmp ax, 2 jl .sig1 mov word [deltax], 2 .sig1: cmp ax, -2 jg .sig2 mov word [deltax], -2 .sig2: calcx: ; 2.- calcular x mov ax, [spritex] mov bx, [deltax] add ax, bx ; 1.1.- revisar que no se salga cmp ax, WIDTHPX - ANCHOSPRITE jng .sig1 mov ax, WIDTHPX - ANCHOSPRITE neg bx .sig1: cmp ax, 0 jnl .sig2 mov ax, 0 neg bx .sig2: mov [spritenx], ax mov [deltax], bx calcdy: ; 2.- Calcular delta Y mov dx, [deltay] add dx, GRAVEDAD mov [deltay], dx calcy: ; 3.- calcular y mov ax, [spritey] mov bx, [deltay] add ax, bx ; 1.1.- revisar que no se salga cmp ax, HEIGHTPX - ALTOSPRITE jng .sig1 mov ax, HEIGHTPX - ALTOSPRITE mov bx, 0 mov word [parado], 1 .sig1: cmp ax, 0 jnl .sig2 mov ax, 0 mov bx, 0 .sig2: mov [spriteny], ax mov [deltay], bx ; Fin de mecanica del juego ret fin: ; 1 .- Reestablecer rutina original de manejo de teclado mov dx,[kb_int_old_off] mov ax,[kb_int_old_seg] mov ds,ax mov al,9h mov ah,25h int 21h ; 2 .- Salir al sistema int 20h dibujasprite16: ; Parametros: ; AX = Coordenada Y ; BX = Coordenada X ; DX = Mapa de bits ; -1.- Revisar si pixeles están alineados con bytes test bx, 0000001b jnz dibujasprite16noalineado shr bx, 1 ; 0.- Respaldar cosas que deberíamos consevar mov si, dx ; Cargar direccion de mapa de bits ; 1.- Seleccionar banco de memoria mov cx, MEMCGAEVEN mov es, cx ; mov cx, ax ; Copiar / respaldar coordenada Y ; shr ax, 1 ; Descartar el bit de selección de banco ; 2.- Multiplicar mov dl, BYTESPERSCAN mul dl ; multiplicar por ancho de pantalla en bytes add ax, bx ; Desplazamiento del byte que vamos a manipular mov di, ax .dibujarenglones: mov cx, ALTOSPRITE ; 4 .- Dibujamos TODOS los renglones (en renglones par de patalla) .looprenglon: movsw movsw movsw movsw add di, BYTESPERSCAN - BWSPRITE; Agregar suficientes bytes para que sea siguiente renglon loop .looprenglon ; 5 .- Después dibujamos mismos renglones de sprite, ahora en renglones impar de pantalla mov cx, es cmp cx, MEMCGAODD je .salir mov cx, MEMCGAODD ; Dibujar en renglones impar de pantalla CGA 4 Col mov es, cx sub di, BYTESPERSCAN * ALTOSPRITE ; Retroceder hasta posicion inicial en pantalla ? (pero ahora en renglon impar) sub si, BWSPRITE * ( ALTOSPRITE ) ; retrocedemos hasta posicion inicial de sprite + un renglon jmp .dibujarenglones ; retorno de la función .salir: ret dibujasprite16noalineado: ; 0.- Respaldar cosas que deberíamos consevar mov si, dx ; Cargar direccion de mapa de bits ; 1.- Seleccionar banco de memoria mov cx, MEMCGAEVEN mov es, cx mov cx, ax ; Copiar / respaldar coordenada Y ; shr ax, 1 ; Descartar el bit de selección de banco ; 2.- Multiplicar mov dl, BYTESPERSCAN mul dl ; multiplicar por ancho de pantalla en bytes mov dx, bx ; Copiar coordenada X shr dx, 1 ; Descartar ultimo bit add ax, dx ; Desplazamiento del byte que vamos a manipular mov di, ax ; and bx, 00000001b ; Usar solo ultimo bit para posicion sub-byte .dibujarenglones: mov cx, ALTOSPRITE ; 4 .- Primero dibujamos TODOS los renglones (en renglones par de patalla) .looprenglon: mov dx, cx ; guardar contador de renglones mov cx, 4 ; guardar bits a desplazar en el contador xor ax, ax ; borrar ax lodsb ; cargar byte en al shr ax, cl ; desplazar esa cantidad de bits stosb ; Escribir byte (?) dec si lodsw xchg ah, al mov cx, 4 shr ax, cl ; desplazar esa cantidad de bits stosb ; Escribir byte (?) dec si lodsw xchg ah, al mov cx, 4 shr ax, cl ; desplazar esa cantidad de bits stosb ; Escribir byte (?) dec si lodsw xchg ah, al mov cx, 4 shr ax, cl ; desplazar esa cantidad de bits stosb ; Escribir byte (?) dec si lodsw xchg ah, al mov cx, 4 shr ax, cl ; desplazar esa cantidad de bits stosb ; Escribir byte (?) dec si lodsw xchg ah, al mov cx, 4 shr ax, cl ; desplazar esa cantidad de bits stosb ; Escribir byte (?) dec si lodsw xchg ah, al mov cx, 4 shr ax, cl ; desplazar esa cantidad de bits stosb ; Escribir byte (?) dec si lodsw xchg ah, al mov cx, 4 shr ax, cl ; desplazar esa cantidad de bits stosb ; Escribir byte (?) xor ax, ax mov ah, [ds:si - 1] mov cx, 4 shr ax, cl stosb ; movsw -- Descartar estos ; movsw add di, ( BYTESPERSCAN - ( ( BWSPRITE + 1 ) ) ) ; Agregar suficientes bytes para que sea siguiente renglon mov cx, dx ; contador de renglones loop .looprenglon ; 5 .- Después dibujamos los mismos renglones de sprite, ahora en renglones impar de pantalla mov cx, es cmp cx, MEMCGAODD je .salir mov cx, MEMCGAODD ; Dibujar en renglones impar de pantalla CGA 4 Col mov es, cx sub di, BYTESPERSCAN * ALTOSPRITE ; Retroceder hasta posicion inicial en pantalla ? (pero ahora en renglon impar) sub si, BWSPRITE * ALTOSPRITE ; retrocedemos hasta posicion inicial de sprite ? jmp .dibujarenglones ; retorno de la función .salir: ret borrasprite16: ; Parametros: ; AX = Coordenada Y ; BX = Coordenada X ; 0.- Respaldar cosas que deberíamos consevar ; 1.- Seleccionar banco de memoria mov cx, MEMCGAEVEN mov es, cx ; mov cx, ax ; Copiar / respaldar coordenada Y ; shr ax, 1 ; Descartar el bit de selección de banco ; Multiplicar mov dl, BYTESPERSCAN mul dl ; multiplicar por ancho de pantalla en bytes shr bx, 1 add ax, bx ; Desplazamiento del byte que vamos a manipular mov di, ax .borrarenglones: mov cx, ALTOSPRITE ; Primero borramos TODOS los renglones del sprite (en renglones par de patalla) xor ax, ax ; Registro AX en ceros .looprenglon: stosw stosw stosw stosw stosb add di, BYTESPERSCAN - ( BWSPRITE + 1 ) ; Agregar suficientes bytes para que sea siguiente renglon loop .looprenglon ; Después dibujamos otra mitad de renglones de sprite, ahora en renglones impar de pantalla mov cx, es cmp cx, MEMCGAODD je .salir mov cx, MEMCGAODD ; Dibujar en renglones impar de pantalla CGA 4 Col mov es, cx sub di, BYTESPERSCAN * ALTOSPRITE ; Retroceder hasta posicion inicial en pantalla ? (pero ahora en renglon impar) jmp .borrarenglones ; retorno de la función .salir: ret section .data ; program data kb_int_old_off: dw 0 kb_int_old_seg: dw 0 ; Estado de las teclas: tecla_esc: db 0 tecla_up: db 0 tecla_down: db 0 tecla_left: db 0 tecla_right: db 0 ; Variables del programa: spritex: dw 40d spritey: dw 92d spritenx: dw 0 spriteny: dw 0 deltax: dw 0 deltay: dw 0 parado: dw 0 paleta: db 1 align 8,db 0 spritepelota: db 00000000b, 00000000b, 00000000b, 00000000b db 00000000b, 00101010b, 10101010b, 00000000b db 00000000b, 10101010b, 10101010b, 10000000b db 00000010b, 10101010b, 10111011b, 10100000b db 00001010b, 10101010b, 10101110b, 10101000b db 00101010b, 10101010b, 10111011b, 10101010b db 00101010b, 10101010b, 10101010b, 10101010b db 00101010b, 10101010b, 10101010b, 10101010b db 00101010b, 10101010b, 10101010b, 10101010b db 00101010b, 01100110b, 10101010b, 10101010b db 00101001b, 10011001b, 10101010b, 10101010b db 00101010b, 01010110b, 10101010b, 10101010b db 00001001b, 10011001b, 10101010b, 10101000b db 00000010b, 01100110b, 10101010b, 10100000b db 00000000b, 10101010b, 10101010b, 10000000b db 00000000b, 00101010b, 10101010b, 00000000b spritemonigote: incbin "monocomposite",0,128 section .bss ; uninitialized data
; A184586: a(n) = floor((n-1/2)*r), where r=sqrt(5); complement of A184587. ; 1,3,5,7,10,12,14,16,19,21,23,25,27,30,32,34,36,39,41,43,45,48,50,52,54,57,59,61,63,65,68,70,72,74,77,79,81,83,86,88,90,92,95,97,99,101,103,106,108,110,112,115,117,119,121,124,126,128,130,133,135,137,139,141,144,146,148,150,153,155,157,159,162,164,166,168,171,173,175,177,180,182,184,186,188,191,193,195,197,200,202,204,206,209,211,213,215,218,220,222,224,226,229,231,233,235,238,240,242,244,247,249,251,253,256,258,260,262,264,267 mov $3,$0 add $3,1 mul $0,$3 mov $1,1 mov $2,4 mov $4,$0 mul $4,5 add $4,1 lpb $2,1 lpb $4,1 add $1,2 trn $4,$1 lpe sub $2,1 lpe sub $1,3 div $1,2 add $1,1
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r14 push %r15 push %rax push %rcx push %rdi push %rsi lea addresses_UC_ht+0xbb92, %r14 nop sub %rsi, %rsi movl $0x61626364, (%r14) nop nop cmp $32474, %r10 lea addresses_UC_ht+0xbde2, %rcx nop and %rax, %rax vmovups (%rcx), %ymm4 vextracti128 $0, %ymm4, %xmm4 vpextrq $1, %xmm4, %r11 nop add %rsi, %rsi lea addresses_D_ht+0x15246, %r11 cmp %r15, %r15 movw $0x6162, (%r11) dec %r11 lea addresses_D_ht+0x1e702, %r10 nop nop nop nop add %rsi, %rsi mov (%r10), %r15d nop nop nop nop nop dec %r11 lea addresses_WT_ht+0x6e2, %rcx nop nop nop sub %rax, %rax mov (%rcx), %r11w nop add $33290, %r14 lea addresses_WC_ht+0x12262, %rsi lea addresses_WT_ht+0x5b18, %rdi nop nop nop sub $31928, %r10 mov $48, %rcx rep movsl nop nop nop nop nop and $44837, %r10 lea addresses_WC_ht+0x19d22, %rsi lea addresses_normal_ht+0x169e2, %rdi nop nop nop add %r10, %r10 mov $18, %rcx rep movsw nop nop nop nop nop cmp $23389, %rdi pop %rsi pop %rdi pop %rcx pop %rax pop %r15 pop %r14 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r8 push %rax push %rbx push %rdi push %rsi // Store lea addresses_PSE+0x5922, %r12 nop cmp $24784, %rsi mov $0x5152535455565758, %r8 movq %r8, %xmm0 vmovups %ymm0, (%r12) and %rbx, %rbx // Store lea addresses_PSE+0x1d9e2, %r12 nop nop sub %rax, %rax movl $0x51525354, (%r12) nop nop nop nop nop and %rdi, %rdi // Faulty Load lea addresses_UC+0x14de2, %r12 nop cmp $23076, %r13 movb (%r12), %r8b lea oracles, %rbx and $0xff, %r8 shlq $12, %r8 mov (%rbx,%r8,1), %r8 pop %rsi pop %rdi pop %rbx pop %rax pop %r8 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'AVXalign': True, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': True, 'congruent': 10, 'size': 4, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 4, 'size': 4, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 11, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 2, 'size': 2, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 2, 'size': 4, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': True, 'congruent': 8, 'size': 2, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A274340: A 4-cycle of the iterated sum of deficient divisors function. ; 19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36,19,20,22,36 mod $0,4 mov $2,2 lpb $0 sub $0,1 mov $1,6 sub $2,1 add $1,$2 pow $1,$0 trn $0,3 add $1,2 lpe div $1,3 add $1,19 mov $0,$1
; A266613: Decimal representation of the middle column of the "Rule 41" elementary cellular automaton starting with a single ON (black) cell. ; 1,2,5,10,20,41,82,165,330,661,1322,2645,5290,10581,21162,42325,84650,169301,338602,677205,1354410,2708821,5417642,10835285,21670570,43341141,86682282,173364565,346729130,693458261,1386916522,2773833045,5547666090,11095332181,22190664362,44381328725,88762657450,177525314901,355050629802,710101259605,1420202519210,2840405038421,5680810076842,11361620153685,22723240307370,45446480614741,90892961229482,181785922458965,363571844917930,727143689835861,1454287379671722,2908574759343445,5817149518686890 add $0,1 mov $2,1 mov $5,1 lpb $0,1 sub $0,1 mov $3,2 mov $7,$2 mul $2,2 sub $3,$5 sub $2,$3 add $2,16 add $7,$5 div $7,2 trn $5,$7 lpe mov $1,4 mov $2,$4 add $2,4 mov $6,1 mul $6,$7 div $6,6 mul $6,2 add $1,$6 add $1,$2 sub $1,7 div $1,2 add $1,1
; A017023: a(n) = (7*n + 3)^7. ; 2187,10000000,410338673,4586471424,27512614111,114415582592,373669453125,1028071702528,2488651484819,5455160701056,11047398519097,20971520000000,37725479487783,64847759419264,107213535210701,171382426877952,266001988046875,402271083010688,594467302491009,860542568759296,1222791080775407,1708593750000000,2351243277537493,3190854023266304,4275360817613091,5661610866627712,7416552901015625,9618527719784448,12358664279161399,15742385477438336,19891027786401117,24943578880000000,31058537410917803,38415899085692544,47219273189051281,57698133708111872,70110209207109375,84744015603303808,101921535994725989,122001051690418176,145380128593826227,172498763090000000,203842691587258713,239946867863977984,281399112371155271,328843937641410432,382986553955078125,444597059414048768,514514818574014779,593653033785778816,683003513396280737,783641640960000000,896731549611390223,1023531505749002624,1165399506181955061,1323799092889403392,1500305389543671875,1696611363947699328,1914534320537457769,2156022627100000256,2423162679857794647,2718186111070000000,3043477243301342333,3401580794509246464,3795209838099880651,4227254022103770752,4700788051621640625,5219080438691135488,5785602523725084959,6404037772671962496,7078291354049197957,7812500000000000000,8611042155524345043,9478548420034789504,10419912285387762041,11440301174540992512,12545167784987734375,13740261741118437248,15031641559660526349,16425686932346945536,17929111329964120667,19548974931930000000,21292697885552828353,23168073899121311744,25183284172976829231,27346911672718348672,29667955748690703125,32155847105906884608,34820463128555011939,37672143563240629376,40721706565114992777,43980465111040000000,47460243783940422263,51173395932494093184,55132821210310712221,59351983498749919232,63844929217529296875,68626306027272957568,73711381928151371729,79116064758763094016 mul $0,7 add $0,3 pow $0,7
/////////////////////////////////////////////////////////////////////////////// // Name: tests/controls/ownerdrawncomboboxtest.cpp // Purpose: OwnerDrawnComboBox unit test // Author: Jaakko Salli // Created: 2010-12-17 // Copyright: (c) 2010 Jaakko Salli /////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #include "testprec.h" #if wxUSE_ODCOMBOBOX #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/app.h" #endif // WX_PRECOMP #include "wx/odcombo.h" #include "textentrytest.h" #include "itemcontainertest.h" #include "testableframe.h" // ---------------------------------------------------------------------------- // test class // ---------------------------------------------------------------------------- class OwnerDrawnComboBoxTestCase : public TextEntryTestCase, public ItemContainerTestCase, public CppUnit::TestCase { public: OwnerDrawnComboBoxTestCase() { } virtual void setUp() wxOVERRIDE; virtual void tearDown() wxOVERRIDE; private: virtual wxTextEntry *GetTestEntry() const wxOVERRIDE { return m_combo; } virtual wxWindow *GetTestWindow() const wxOVERRIDE { return m_combo; } virtual wxItemContainer *GetContainer() const wxOVERRIDE { return m_combo; } virtual wxWindow *GetContainerWindow() const wxOVERRIDE { return m_combo; } virtual void CheckStringSelection(const char * WXUNUSED(sel)) wxOVERRIDE { // do nothing here, as explained in TextEntryTestCase comment, our // GetStringSelection() is the wxChoice, not wxTextEntry, one and there // is no way to return the selection contents directly } CPPUNIT_TEST_SUITE( OwnerDrawnComboBoxTestCase ); wxTEXT_ENTRY_TESTS(); wxITEM_CONTAINER_TESTS(); CPPUNIT_TEST( Size ); CPPUNIT_TEST( PopDismiss ); CPPUNIT_TEST( Sort ); CPPUNIT_TEST( ReadOnly ); CPPUNIT_TEST_SUITE_END(); void Size(); void PopDismiss(); void Sort(); void ReadOnly(); wxOwnerDrawnComboBox *m_combo; wxDECLARE_NO_COPY_CLASS(OwnerDrawnComboBoxTestCase); }; wxREGISTER_UNIT_TEST_WITH_TAGS(OwnerDrawnComboBoxTestCase, "[OwnerDrawnComboBoxTestCase][item-container]"); // ---------------------------------------------------------------------------- // test initialization // ---------------------------------------------------------------------------- void OwnerDrawnComboBoxTestCase::setUp() { m_combo = new wxOwnerDrawnComboBox(wxTheApp->GetTopWindow(), wxID_ANY); } void OwnerDrawnComboBoxTestCase::tearDown() { delete m_combo; m_combo = NULL; } // ---------------------------------------------------------------------------- // tests themselves // ---------------------------------------------------------------------------- void OwnerDrawnComboBoxTestCase::Size() { // under MSW changing combobox size is a non-trivial operation because of // confusion between the size of the control with and without dropdown, so // check that it does work as expected const int heightOrig = m_combo->GetSize().y; // check that the height doesn't change if we don't touch it m_combo->SetSize(100, -1); CPPUNIT_ASSERT_EQUAL( heightOrig, m_combo->GetSize().y ); // check that setting both big and small (but not too small, there is a // limit on how small the control can become under MSW) heights works m_combo->SetSize(-1, 50); CPPUNIT_ASSERT_EQUAL( 50, m_combo->GetSize().y ); m_combo->SetSize(-1, 10); CPPUNIT_ASSERT_EQUAL( 10, m_combo->GetSize().y ); // and also that restoring it works (this used to be broken before 2.9.1) m_combo->SetSize(-1, heightOrig); CPPUNIT_ASSERT_EQUAL( heightOrig, m_combo->GetSize().y ); } void OwnerDrawnComboBoxTestCase::PopDismiss() { EventCounter drop(m_combo, wxEVT_COMBOBOX_DROPDOWN); EventCounter close(m_combo, wxEVT_COMBOBOX_CLOSEUP); m_combo->Popup(); m_combo->Dismiss(); CPPUNIT_ASSERT_EQUAL(1, drop.GetCount()); CPPUNIT_ASSERT_EQUAL(1, close.GetCount()); } void OwnerDrawnComboBoxTestCase::Sort() { delete m_combo; m_combo = new wxOwnerDrawnComboBox(wxTheApp->GetTopWindow(), wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_SORT); m_combo->Append("aaa"); m_combo->Append("Aaa"); m_combo->Append("aba"); m_combo->Append("aaab"); m_combo->Append("aab"); m_combo->Append("AAA"); CPPUNIT_ASSERT_EQUAL("AAA", m_combo->GetString(0)); CPPUNIT_ASSERT_EQUAL("Aaa", m_combo->GetString(1)); CPPUNIT_ASSERT_EQUAL("aaa", m_combo->GetString(2)); CPPUNIT_ASSERT_EQUAL("aaab", m_combo->GetString(3)); CPPUNIT_ASSERT_EQUAL("aab", m_combo->GetString(4)); CPPUNIT_ASSERT_EQUAL("aba", m_combo->GetString(5)); m_combo->Append("a"); CPPUNIT_ASSERT_EQUAL("a", m_combo->GetString(0)); } void OwnerDrawnComboBoxTestCase::ReadOnly() { wxArrayString testitems; testitems.Add("item 1"); testitems.Add("item 2"); delete m_combo; m_combo = new wxOwnerDrawnComboBox(wxTheApp->GetTopWindow(), wxID_ANY, "", wxDefaultPosition, wxDefaultSize, testitems, wxCB_READONLY); m_combo->SetValue("item 1"); CPPUNIT_ASSERT_EQUAL("item 1", m_combo->GetValue()); m_combo->SetValue("not an item"); CPPUNIT_ASSERT_EQUAL("item 1", m_combo->GetValue()); // Since this uses FindString it is case insensitive m_combo->SetValue("ITEM 2"); CPPUNIT_ASSERT_EQUAL("item 2", m_combo->GetValue()); } #endif // wxUSE_ODCOMBOBOX
; Wkst12plus1.asm - DifferentInputs returns EAX=1 if the values of its three input parameters are all different; otherwise, return with EAX=0 .386 .model flat, stdcall .stack 4096 ExitProcess proto, dwExitCode:dword DifferentInputs proto num1:dword, num2:dword, num3:dword .data val1 DWORD 20h val2 DWORD 33h val3 DWORD 4ah .code main proc invoke DifferentInputs, val1, val2, val3 invoke ExitProcess, 0 main endp DifferentInputs proc, num1:dword, num2:dword, num3:dword mov eax, 1 mov num1, eax cmp num2, eax je L2 cmp num3, eax je L2 jmp exit L2: mov eax, 0 exit: ret DifferentInputs endp end main
; A157732: a(n) = 388962*n^2 - 430416*n + 119071. ; 77617,814087,2328481,4620799,7691041,11539207,16165297,21569311,27751249,34711111,42448897,50964607,60258241,70329799,81179281,92806687,105212017,118395271,132356449,147095551,162612577,178907527,195980401,213831199,232459921,251866567,272051137,293013631,314754049,337272391,360568657,384642847,409494961,435124999,461532961,488718847,516682657,545424391,574944049,605241631,636317137,668170567,700801921,734211199,768398401,803363527,839106577,875627551,912926449,951003271,989858017,1029490687,1069901281,1111089799,1153056241,1195800607,1239322897,1283623111,1328701249,1374557311,1421191297,1468603207,1516793041,1565760799,1615506481,1666030087,1717331617,1769411071,1822268449,1875903751,1930316977,1985508127,2041477201,2098224199,2155749121,2214051967,2273132737,2332991431,2393628049,2455042591,2517235057,2580205447,2643953761,2708479999,2773784161,2839866247,2906726257,2974364191,3042780049,3111973831,3181945537,3252695167,3324222721,3396528199,3469611601,3543472927,3618112177,3693529351,3769724449,3846697471,3924448417,4002977287,4082284081,4162368799,4243231441,4324872007,4407290497,4490486911,4574461249,4659213511,4744743697,4831051807,4918137841,5006001799,5094643681,5184063487,5274261217,5365236871,5456990449,5549521951,5642831377,5736918727,5831784001,5927427199,6023848321,6121047367,6219024337,6317779231,6417312049,6517622791,6618711457,6720578047,6823222561,6926644999,7030845361,7135823647,7241579857,7348113991,7455426049,7563516031,7672383937,7782029767,7892453521,8003655199,8115634801,8228392327,8341927777,8456241151,8571332449,8687201671,8803848817,8921273887,9039476881,9158457799,9278216641,9398753407,9520068097,9642160711,9765031249,9888679711,10013106097,10138310407,10264292641,10391052799,10518590881,10646906887,10776000817,10905872671,11036522449,11167950151,11300155777,11433139327,11566900801,11701440199,11836757521,11972852767,12109725937,12247377031,12385806049,12525012991,12664997857,12805760647,12947301361,13089619999,13232716561,13376591047,13521243457,13666673791,13812882049,13959868231,14107632337,14256174367,14405494321,14555592199,14706468001,14858121727,15010553377,15163762951,15317750449,15472515871,15628059217,15784380487,15941479681,16099356799,16258011841,16417444807,16577655697,16738644511,16900411249,17062955911,17226278497,17390379007,17555257441,17720913799,17887348081,18054560287,18222550417,18391318471,18560864449,18731188351,18902290177,19074169927,19246827601,19420263199,19594476721,19769468167,19945237537,20121784831,20299110049,20477213191,20656094257,20835753247,21016190161,21197404999,21379397761,21562168447,21745717057,21930043591,22115148049,22301030431,22487690737,22675128967,22863345121,23052339199,23242111201,23432661127,23623988977,23816094751,24008978449,24202640071 mul $0,9 mov $4,-4 sub $4,$0 mov $0,1 mov $1,1 mov $2,1 mov $3,5 mov $5,49 mul $5,$4 sub $1,$5 pow $1,2 add $1,3 mov $6,1 lpb $0,1 sub $0,1 mul $2,2 mul $3,$2 add $6,5 mul $1,$6 add $1,$3 lpe sub $1,232882 div $1,2646 mul $1,882 add $1,77617
; A281452: Expansion of f(x, x) * f(x^5, x^13) in powers of x where f(, ) is Ramanujan's general theta function. ; Submitted by Christian Krause ; 1,2,0,0,2,1,2,0,0,4,0,0,0,1,4,0,2,2,0,0,0,2,2,0,0,2,0,0,1,4,2,0,2,0,0,0,2,2,2,0,0,2,0,0,3,2,0,0,2,4,0,0,0,4,2,0,0,0,0,0,2,0,2,0,4,0,0,0,0,5,2,0,0,2,0,0,0,4,2,0,2,2,0,0,0,2,2,0,0,0,0,0,2,3,6,0,0,2,0,0 mul $0,9 add $0,3 seq $0,2654 ; Number of ways of writing n as a sum of at most two nonzero squares, where order matters; also (number of divisors of n of form 4m+1) - (number of divisors of form 4m+3).
; A057038: Let R(i,j) be the rectangle with antidiagonals 1; 2,3; 4,5,6; ...; each k is an R(i(k),j(k)) and A057038(n)=i(2n). ; 1,1,3,2,4,2,4,1,3,5,1,3,5,7,2,4,6,8,2,4,6,8,1,3,5,7,9,1,3,5,7,9,11,2,4,6,8,10,12,2,4,6,8,10,12,1,3,5,7,9,11,13,1,3,5,7,9,11,13,15,2,4,6,8,10,12,14,16,2,4,6,8,10,12,14,16,1,3,5,7,9 mul $0,2 add $0,2 lpb $0 mov $1,$0 add $2,1 trn $0,$2 lpe
; SPIR-V ; Version: 1.0 ; Generator: Khronos Glslang Reference Front End; 10 ; Bound: 58 ; Schema: 0 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" %39 OpExecutionMode %4 OriginUpperLeft OpSource ESSL 320 OpName %4 "main" OpName %8 "f" OpName %13 "buf0" OpMemberName %13 0 "_GLF_uniform_int_values" OpName %15 "" OpName %27 "buf1" OpMemberName %27 0 "_GLF_uniform_float_values" OpName %29 "" OpName %39 "_GLF_color" OpDecorate %12 ArrayStride 16 OpMemberDecorate %13 0 Offset 0 OpDecorate %13 Block OpDecorate %15 DescriptorSet 0 OpDecorate %15 Binding 0 OpDecorate %26 ArrayStride 16 OpMemberDecorate %27 0 Offset 0 OpDecorate %27 Block OpDecorate %29 DescriptorSet 0 OpDecorate %29 Binding 1 OpDecorate %39 Location 0 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeFloat 32 %7 = OpTypePointer Function %6 %9 = OpTypeInt 32 1 %10 = OpTypeInt 32 0 %11 = OpConstant %10 2 %12 = OpTypeArray %9 %11 %13 = OpTypeStruct %12 %14 = OpTypePointer Uniform %13 %15 = OpVariable %14 Uniform %16 = OpConstant %9 0 %17 = OpConstant %9 1 %18 = OpTypePointer Uniform %9 %25 = OpConstant %10 1 %26 = OpTypeArray %6 %25 %27 = OpTypeStruct %26 %28 = OpTypePointer Uniform %27 %29 = OpVariable %28 Uniform %30 = OpTypePointer Uniform %6 %33 = OpTypeBool %37 = OpTypeVector %6 4 %38 = OpTypePointer Output %37 %39 = OpVariable %38 Output %4 = OpFunction %2 None %3 %5 = OpLabel %8 = OpVariable %7 Function %19 = OpAccessChain %18 %15 %16 %17 %20 = OpLoad %9 %19 %21 = OpConvertSToF %6 %20 %22 = OpExtInst %6 %1 Trunc %21 %23 = OpExtInst %6 %1 Fract %22 OpStore %8 %23 %24 = OpLoad %6 %8 %31 = OpAccessChain %30 %29 %16 %16 %32 = OpLoad %6 %31 %34 = OpFOrdEqual %33 %24 %32 OpSelectionMerge %36 None OpBranchConditional %34 %35 %53 %35 = OpLabel %40 = OpAccessChain %18 %15 %16 %17 %41 = OpLoad %9 %40 %42 = OpConvertSToF %6 %41 %43 = OpAccessChain %18 %15 %16 %16 %44 = OpLoad %9 %43 %45 = OpConvertSToF %6 %44 %46 = OpAccessChain %18 %15 %16 %16 %47 = OpLoad %9 %46 %48 = OpConvertSToF %6 %47 %49 = OpAccessChain %18 %15 %16 %17 %50 = OpLoad %9 %49 %51 = OpConvertSToF %6 %50 %52 = OpCompositeConstruct %37 %42 %45 %48 %51 OpStore %39 %52 OpBranch %36 %53 = OpLabel %54 = OpAccessChain %18 %15 %16 %16 %55 = OpLoad %9 %54 %56 = OpConvertSToF %6 %55 %57 = OpCompositeConstruct %37 %56 %56 %56 %56 OpStore %39 %57 OpBranch %36 %36 = OpLabel OpReturn OpFunctionEnd
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_VehicleSimApiBase_hpp #define air_VehicleSimApiBase_hpp #include "common/CommonStructs.hpp" #include "common/UpdatableObject.hpp" #include "common/ImageCaptureBase.hpp" #include "physics/Kinematics.hpp" #include "physics/Environment.hpp" #include "common/AirSimSettings.hpp" namespace msr { namespace airlib { class VehicleSimApiBase : public msr::airlib::UpdatableObject { public: virtual ~VehicleSimApiBase() = default; virtual void update() override { UpdatableObject::update(); } //this method is called at every render tick when we want to transfer state from //physics engine to render engine. As physics engine is halted while //this happens, this method should do minimal processing virtual void updateRenderedState(float dt) { unused(dt); //derived class should override if needed } //called when render changes are required at every render tick virtual void updateRendering(float dt) { unused(dt); //derived class should override if needed } virtual const ImageCaptureBase* getImageCapture() const = 0; virtual ImageCaptureBase* getImageCapture() { return const_cast<ImageCaptureBase*>(static_cast<const VehicleSimApiBase*>(this)->getImageCapture()); } virtual void initialize() = 0; virtual bool testLineOfSightToPoint(const GeoPoint& point) const = 0; virtual Pose getPose() const = 0; virtual void setPose(const Pose& pose, bool ignore_collision) = 0; virtual const Kinematics::State* getGroundTruthKinematics() const = 0; virtual const msr::airlib::Environment* getGroundTruthEnvironment() const = 0; virtual CollisionInfo getCollisionInfo() const = 0; virtual int getRemoteControlID() const = 0; //which RC to use, 0 is first one, -1 means disable RC (use keyborad) virtual RCData getRCData() const = 0; //get reading from RC from simulator's host OS virtual std::string getVehicleName() const = 0; virtual std::string getRecordFileLine(bool is_header_line) const = 0; virtual void toggleTrace() = 0; virtual void setTraceLine(const std::vector<float>& color_rgba, float thickness) = 0; //use pointer here because of derived classes for VehicleSetting const AirSimSettings::VehicleSetting* getVehicleSetting() const { return AirSimSettings::singleton().getVehicleSetting(getVehicleName()); } }; } } //namespace #endif
STRUCT MENU_T addr DW items DB height DB y_row DB y_pixel DB width DB x DB x_logo DB ENDS STRUCT MENUENTRY_T text_addr DW value_cb_addr DW callback DW reserved DW ENDS MACRO MENU_DEF width MENU_T { ($+MENU_T) (((.end-$)/MENUENTRY_T-1)) (((.end-$)/MENUENTRY_T-1)+2) ( (24-(((.end-$)/MENUENTRY_T-1)+2))/2) (((24-(((.end-$)/MENUENTRY_T-1)+2))/2)*8) (width) ( (32-width)/2) (((32-width)/2)+width-6) } ENDM menudefault: MENU_DEF 20 MENUENTRY_T str_cpu menu_clock_value_cb menu_clock_cb MENUENTRY_T str_machine menu_machine_value_cb menu_machine_cb MENUENTRY_T str_panning menu_panning_value_cb menu_panning_cb MENUENTRY_T str_joystick menu_joystick_value_cb menu_joystick_cb IFNDEF SIZIFXXS MENUENTRY_T str_rom48 menu_rom48_value_cb menu_rom48_cb ENDIF MENUENTRY_T str_sd menu_sd_value_cb menu_sd_cb MENUENTRY_T str_ulaplus menu_ulaplus_value_cb menu_ulaplus_cb MENUENTRY_T str_dac menu_dac_value_cb menu_dac_cb MENUENTRY_T str_spk menu_spk_value_cb menu_spk_cb MENUENTRY_T str_menuadv 0 menu_menuadv_cb MENUENTRY_T str_exit menu_exit_value_cb menu_exit_cb MENUENTRY_T 0 .end: menuext: MENU_DEF 20 MENUENTRY_T str_cpu menu_clock_value_cb menu_clock_cb MENUENTRY_T str_machine menu_machine_value_cb menu_machine_cb MENUENTRY_T str_panning menu_panning_value_cb menu_panning_cb MENUENTRY_T str_joystick menu_joystick_value_cb menu_joystick_cb MENUENTRY_T str_rom48 menu_rom48_value_cb menu_rom48_cb MENUENTRY_T str_sd menu_sd_value_cb menu_sd_cb MENUENTRY_T str_ulaplus menu_ulaplus_value_cb menu_ulaplus_cb MENUENTRY_T str_dac menu_dac_value_cb menu_dac_cb MENUENTRY_T str_tsfm menu_tsfm_value_cb menu_tsfm_cb MENUENTRY_T str_saa menu_saa_value_cb menu_saa_cb MENUENTRY_T str_gs menu_gs_value_cb menu_gs_cb MENUENTRY_T str_spk menu_spk_value_cb menu_spk_cb MENUENTRY_T str_menuadv 0 menu_menuadv_cb MENUENTRY_T str_exit menu_exit_value_cb menu_exit_cb MENUENTRY_T 0 .end: menuadv: MENU_DEF 22 MENUENTRY_T str_sd_indication menu_sdind_value_cb menu_sdind_cb MENUENTRY_T str_bright_boost menu_bright_value_cb menu_bright_cb MENUENTRY_T str_save_settings menu_cfgsave_value_cb menu_cfgsave_cb MENUENTRY_T str_back 0 menu_back_cb MENUENTRY_T 0 .end: menuboot: MENU_DEF 16 MENUENTRY_T str_normal_boot 0 menu_boot_normal_cb IFNDEF REV_C MENUENTRY_T str_zx80 0 menu_boot_zx80_cb MENUENTRY_T str_zx81 0 menu_boot_zx81_cb MENUENTRY_T str_negluk 0 menu_boot_negluk_cb ENDIF MENUENTRY_T 0 .end: menu_machine_value_cb: ld ix, .values_table ld a, (cfg.machine) jp menu_value_get .values_table: DW str_machine_48_end-2 DW str_machine_128_end-2 DW str_machine_3e_end-2 DW str_machine_pentagon_end-2 menu_clock_value_cb: ld ix, .values_table ld a, (cfg.clock) jp menu_value_get .values_table: DW str_cpu_35_end-2 DW str_cpu_44_end-2 DW str_cpu_52_end-2 DW str_cpu_7_end-2 DW str_cpu_14_end-2 menu_panning_value_cb: ld ix, .values_table ld a, (var_ext_presence) ; if (ext_board && tsfm) - use ABC instead of ACB panning or a ; ... jr z, .no_tsfm ; ... ld a, (cfgext.tsfm) ; ... or a ; ... jr z, .no_tsfm ; ... ld a, (cfg.panning) cp a, 2 ; if (panning == acb) panning = abc jr c, .get ; ... dec a ; ... .get jp menu_value_get .no_tsfm: ld a, (cfg.panning) jp menu_value_get .values_table: DW str_panning_mono_end-2 DW str_panning_abc_end-2 DW str_panning_acb_end-2 menu_joystick_value_cb: ld ix, .values_table ld a, (cfg.joystick) jp menu_value_get .values_table: DW str_joystick_kempston_end-2 DW str_joystick_sinclair_end-2 menu_rom48_value_cb: ld ix, .values_table ld a, (cfg.rom48) jp menu_value_get .values_table: DW str_rom48_default_end-2 DW str_rom48_lg_end-2 DW str_rom48_opense_end-2 menu_sd_value_cb: ld ix, .values_table ld a, (cfg.sd) jp menu_value_get .values_table: DW str_off_end-2 DW str_divmmc_end-2 DW str_zc3e_end-2 menu_ulaplus_value_cb: ld ix, .values_table ld a, (cfg.ulaplus) jp menu_value_get .values_table: DW str_off_end-2 DW str_on_end-2 menu_dac_value_cb: ld ix, .values_table ld a, (cfg.dac) jp menu_value_get .values_table: DW str_off_end-2 DW str_dac_covox_end-2 DW str_dac_sd_end-2 DW str_dac_covoxsd_end-2 menu_spk_value_cb: ld ix, .values_table ld a, (cfg.spk) jp menu_value_get .values_table: DW str_off_end-2 DW str_on_end-2 menu_tsfm_value_cb: ld ix, .values_table ld a, (cfgext.tsfm) jp menu_value_get .values_table: DW str_off_end-2 DW str_on_end-2 menu_saa_value_cb: ld ix, .values_table ld a, (cfgext.saa) jp menu_value_get .values_table: DW str_off_end-2 DW str_on_end-2 menu_gs_value_cb: ld ix, .values_table ld a, (cfgext.gs) jp menu_value_get .values_table: DW str_off_end-2 DW str_on_end-2 menu_exit_value_cb: ld ix, .values_table ld a, (var_exit_reboot) jp menu_value_get .values_table: DW str_exit_no_reboot_end-2 DW str_exit_reboot_end-2 menu_sdind_value_cb: ld ix, .values_table ld a, (cfg.sdind) jp menu_value_get .values_table: DW str_off_short_end-2 DW str_on_short_end-2 menu_bright_value_cb: ld ix, .values_table ld a, (cfg.bright) jp menu_value_get .values_table: DW str_off_short_end-2 DW str_on_short_end-2 menu_cfgsave_value_cb: ld ix, .values_table ld a, (var_flash_error) jp menu_value_get .values_table: DW str_no_error_end-2 DW str_error_end-2 menu_value_get: sla a ld c, a ld b, 0 add ix, bc ld l, (ix+0) ld h, (ix+1) ret menu_machine_cb: ld a, (cfg.machine) ld c, 3 call menu_handle_press ld (cfg.machine), a ld bc, #02ff out (c), a ret menu_clock_cb: ld a, (cfg.clock) ld c, 4 call menu_handle_press ld (cfg.clock), a ld bc, #03ff out (c), a ret menu_panning_cb: ld a, (var_ext_presence) ; if (ext_board && tsfm) - do not allow to set ACB panning or a ; ... jr z, .no_tsfm ; ... ld a, (cfgext.tsfm) ; ... or a ; ... jr z, .no_tsfm ; ... ld a, (cfg.panning) ; ... ld c, 1 ; ... jr .load .no_tsfm: ld a, (cfg.panning) ld c, 2 .load: call menu_handle_press ld (cfg.panning), a ld bc, #04ff out (c), a ret menu_joystick_cb: ld a, (cfg.joystick) ld c, 1 call menu_handle_press ld (cfg.joystick), a ld bc, #07ff out (c), a ret menu_rom48_cb: ld a, (cfg.rom48) IFDEF REV_C ld c, 1 ELSE ld c, 2 ENDIF call menu_handle_press ld (cfg.rom48), a ld bc, #06ff out (c), a ret menu_sd_cb: ld a, (cfg.sd) ld c, 2 call menu_handle_press ld (cfg.sd), a ld bc, #09ff out (c), a ret menu_ulaplus_cb: ld a, (cfg.ulaplus) ld c, 1 call menu_handle_press ld (cfg.ulaplus), a ld bc, #0aff out (c), a ret menu_dac_cb: ld a, (cfg.dac) ld c, 3 call menu_handle_press ld (cfg.dac), a ld bc, #0bff out (c), a ret menu_spk_cb: ld a, (cfg.spk) ld c, 1 call menu_handle_press ld (cfg.spk), a ld bc, #0cff out (c), a ret menu_tsfm_cb: ld a, (cfgext.tsfm) ld c, 1 call menu_handle_press ld (cfgext.tsfm), a ld bc, #e1ff out (c), a ret menu_saa_cb: ld a, (cfgext.saa) ld c, 1 call menu_handle_press ld (cfgext.saa), a ld bc, #e2ff out (c), a ret menu_gs_cb: ld a, (cfgext.gs) ld c, 1 call menu_handle_press ld (cfgext.gs), a ld bc, #e3ff out (c), a ret menu_exit_cb: bit 4, d ; action? jr nz, .exit ld a, (var_exit_reboot) ld c, 1 call menu_handle_press ld (var_exit_reboot), a ret .exit ld a, 1 ld (var_exit_flag), a ret menu_menuadv_cb: ld hl, menuadv call menu_init ret menu_sdind_cb: ld a, (cfg.sdind) ld c, 1 call menu_handle_press ld (cfg.sdind), a ld bc, #0cff out (c), a ret menu_bright_cb: ld a, (cfg.bright) ld c, 1 call menu_handle_press ld (cfg.bright), a ld bc, #0dff out (c), a ret menu_cfgsave_cb: bit 4, d ; action? ret z call save_user_config or a ; a == 1 means error ret nz ; ... push de ld a, 1 ld b, SAVE_ANIMATION_LEN ; show some border effect to provide feedback about operation .loop: ; ... push bc ; ... call .save_animation_effect ; ... pop bc ; ... djnz .loop ; ... pop de ret .save_animation_effect: ld e, 255 .loop_outer: inc a ; toggle border and 1 ; ... ld bc, #01ff ; ... out (c), a ; ... ld d, 255 .loop_inner: dec d jr nz, .loop_inner dec e jr nz, .loop_outer ret menu_back_cb: call restore_screen ld hl, (var_menumain) jp menu_init menu_boot_normal_cb: bit 4, d ; action? ret z ld a, 0 ld (cfg_saved.custom_rom), a ld a, 1 ld (var_exit_flag), a ret menu_boot_zx80_cb: bit 4, d ; action? ret z ld a, #81 ld (cfg_saved.custom_rom), a ld a, 1 ld (var_exit_flag), a ret menu_boot_zx81_cb: bit 4, d ; action? ret z ld a, #80 ld (cfg_saved.custom_rom), a ld a, 1 ld (var_exit_flag), a ret menu_boot_negluk_cb: bit 4, d ; action? ret z ld a, #83 ld (cfg_saved.custom_rom), a ld a, 1 ld (var_exit_flag), a ret ; IN - A - variable to change ; IN - C - max value ; IN - D - pressed key ; OUT - A - new variable value menu_handle_press: bit 4, d ; action? jr nz, .increment bit 0, d ; right? jr nz, .increment bit 1, d ; left? jr nz, .decrement ret .increment: cp c ; if (value >= max) value = 0 jr nc, .increment_roll ; ... inc a ; else value++ ret .increment_roll: xor a ; value = 0 ret .decrement: or a ; if (value == 0) value = max jr z, .decrement_roll ; ... dec a ; else value-- ret .decrement_roll: ld a, c ; value = max ret
#ifndef SORT_H_ODDERIKF #define SORT_H_ODDERIKF namespace my { template<typename I> void insertsort(I low, I high); template<typename L> bool verify(L &list); template<typename I> void quickinsertsort(I low, I high); template<typename I> void quicksort(I low, I high); template<typename I> void doublepivotquicksort(I low, I high); #include "sort_impl.hpp" } #endif
#include <algorithm> using namespace std; #include <ossim/vec/ossimVpfFeatureClass.h> #include <ossim/base/ossimFilename.h> #include <ossim/vec/ossimVpfCoverage.h> #include <ossim/base/ossimErrorCodes.h> #include <ossim/vec/ossimVpfTable.h> #include <string.h> #ifndef NULL #include <stddef.h> #endif ossimVpfFeatureClass::ossimVpfFeatureClass() { } bool ossimVpfFeatureClass::openFeatureClass(const ossimString& featureClassName, const ossimFilename& featureClassFullPath, const ossimFilename& table1, const ossimString& columnNameIdTable1, const ossimFilename& table2, const ossimString& columnNameIdTable2) { theFeatureClassFullPath = featureClassFullPath; theFeatureClassName = featureClassName; theTableName1 = table1; theColumnNameId1 = columnNameIdTable1; theTableName2 = table2; theColumnNameId2 = columnNameIdTable2; ossimVpfTable t1; ossimVpfTable t2; ossimFilename t1Name = getTable1(); ossimFilename t2Name = getTable2(); if((!t1.openTable(t1Name))|| (!t2.openTable(t2Name))) { return false; } return true; } const ossimString& ossimVpfFeatureClass::getName()const { return theFeatureClassName; } bool ossimVpfFeatureClass::isPrimitive(const ossimString& featureName) { // make sure we have forward slashes ossimFilename filename(featureName.trim()); // filename.convertBackToForwardSlashes(); ossimString copyOfFeature = filename; // find const char* temp = strrchr(copyOfFeature.c_str(), '/'); ossimString value; if(temp) { ++temp; value = temp; } else { value = copyOfFeature; } value = value.downcase(); return( (value == "end") || (value == "cnd") || (value == "edg") || (value == "fac") || (value == "txt") ); } bool ossimVpfFeatureClass::isSimpleFeature(const ossimString& featureName) { // find the suffix ossimString value = strrchr(featureName.trim().c_str(), '.'); // the suffix will be null or empty string if not found. if(value == "") { return false; } // make case insensitive value = value.downcase(); return ( (value == ".pft")|| (value == ".lft")|| (value == ".aft")|| (value == ".tft")); } bool ossimVpfFeatureClass::isComplexFeature(const ossimString& featureName) { const char* suffix = strrchr(featureName.trim(), '.'); if (!suffix) { return false; } ossimString value = ossimString(suffix).downcase(); return (value == ".cft"); } bool ossimVpfFeatureClass::isFeature(const ossimString& featureName) { return (isSimpleFeature(featureName) || isComplexFeature(featureName)); } bool ossimVpfFeatureClass::isJoin(const ossimString& featureName) { ossimString value = strrchr(featureName.c_str(), '.'); if(value == "") { return false; } value = value.downcase(); return ( (value == ".cjt")|| (value == ".pjt")|| (value == ".ljt")|| (value == ".ajt")|| (value == ".tjt")); } ossimFilename ossimVpfFeatureClass::getTable1()const { return theFeatureClassFullPath.dirCat(theTableName1); } ossimFilename ossimVpfFeatureClass::getTable2()const { return theFeatureClassFullPath.dirCat(theTableName2); }
;; ######################################################################## ;; Macros ;; ######################################################################## ; descriptor type, base, limit, p_dpl_s, g_db_a %macro descriptor 5 dw (%3 & 0xFFFF) ; Limit 0-15 dw (%2 & 0xFFFF) ; Base 0-15 db ((%2 & 0xFF0000) >> 16) ; Base 16-23 db ((%4 & 0xF) << 4) | (%1 & 0xF ) ; p_dpl_s_type db (%5 << 4) | ((%3 & 0xF0000) >> 16) ; g_db_a limit 19:16 db ((%2 & 0xFF000000) >> 24) ; Base 24-31 %endmacro ; cdesc32 base, limit, dpl %macro cdesc32 3 descriptor 0xB, %1, %2, 0x9 | (%3 & 0x3) << 1, 0xD %endmacro ; ddesc32 base, limit, dpl %macro ddesc32 3 descriptor 0x3, %1, %2, 0x9 | (%3 & 0x3) << 1, 0xD %endmacro ; gates type, offset, selector, p_dpl_s %macro gates 4 dw %2 ; Offset 0-15 dw (%3 & 0xFFFF) ; Selector 0-15 db 0 ; Reserved db ((%4 & 0xF) << 4) | (%1 & 0xF) ; p_dpl_s_type dw 0 ; Offset 16-31 %endmacro %macro idesc32 3 gates 0xE, %1, %2, 0x8 | ((%3 & 0x3) << 1) %endmacro ;; ######################################################################## ;; Code Section ;; ######################################################################## SECTION CODE ABSOLUTE=0x00400000 FLAT USE32 test_code: ;; Your Code Goes Here hlt ;; ######################################################################## ;; Setup Section ;; ######################################################################## SECTION SETUP ALIGN=16 FLAT USE16 setup: mov edx, cr0 or dl, 0x21 ; Protect Mode On, Int 16 for FPU and edx, 0x9FFFFFFF ; Turn Caches on mov cr0, edx xor edx, edx ; Enable Var MTRRs mov eax, 0x0806 ; WriteBack mov ecx, 0x2FF wrmsr lgdt [pgdt] ; Set GDT lidt [pidt] ; Set IDT jmp 0x8:protect_mode protect_mode: BITS 32 mov esp, 0x01000000 ; Get some stack space mov ax, 0x0010 ; Set data selectors mov ss, ax mov ds, ax mov es, ax mov fs, ax mov gs, ax jmp test_code ; Jmp to test code ;; ######################################################################## ;; Protect Mode IDT ;; ######################################################################## SECTION IDTP ALIGN=16 FLAT USE32 ;; cdesc32 base, limit, dpl gdt0: dq 0.0 ; 0x0000 - Null descriptor cdesc32 0x00000000, 0xFFFFF, 0 ; 0x0008 - Code Selector ddesc32 0x00000000, 0xFFFFF, 0 ; 0x0010 - Data Selector cdesc32 0x00000000, 0xFFFFF, 3 ; 0x0018 - Code Select Ring 3 ddesc32 0x00000000, 0xFFFFF, 3 ; 0x0020 - Data Select Ring 3 ;; idesc32 offset, selector, dpl idt0: idesc32 isrP, 0x0008, 0 ; 0x00, 0 #DE, Divide Error idesc32 isrP, 0x0008, 0 ; 0x01, 1 #DB, Debug Fault idesc32 isrP, 0x0008, 0 ; 0x02, 2, ---, NMI idesc32 isrP, 0x0008, 0 ; 0x03, 3, #BP, Breakpoint idesc32 isrP, 0x0008, 0 ; 0x04, 4, #OF, INTO detected Overflow idesc32 isrP, 0x0008, 0 ; 0x05, 5, #BR, Bound Range Exceeded idesc32 isrP, 0x0008, 0 ; 0x06, 6, #UD, Invalid Opcode idesc32 isrP, 0x0008, 0 ; 0x07, 7, #NM, Device Not Available idesc32 isrP, 0x0008, 0 ; 0x08, 8, #DF, Double Fault idesc32 isrP, 0x0008, 0 ; 0x09 9, ---, Coprocessor Segment Overrun idesc32 isrP, 0x0008, 0 ; 0x0A, 10, #TS, Invalid TSS idesc32 isrP, 0x0008, 0 ; 0x0B, 11, #NP, Segment Not Present idesc32 isrP, 0x0008, 0 ; 0x0C, 12, #SS, Stack Fault idesc32 isrP, 0x0008, 0 ; 0x0D, 13, #GP, General Protection Fault idesc32 isrP, 0x0008, 0 ; 0x0E, 14, #PF, Page Fault idesc32 isrP, 0x0008, 0 ; 0x0F, 15, ---, Reserved idesc32 isrP, 0x0008, 0 ; 0x10, 16, #MF, Floating Point Fault idesc32 isrP, 0x0008, 0 ; 0x11, 17, #AC, Alignment Check idesc32 isrP, 0x0008, 0 ; 0x12 18, #MC, Machine Check idesc32 isrP, 0x0008, 0 ; 0x13, 19, #XF, SSE Fault pgdt: dw 6 * 8 ; Limit dd gdt0 ; base pidt: dw 20 * 8 ; Limit dd idt0 ; base isrP: mov eax, 0xDEADBEEF ; Default Real Mode Interrupt Handler out 0x80, eax hlt ;; ######################################################################## ;; Real Mode IDT ;; ######################################################################## SECTION IDTR ABSOLUTE=0x00000000 FLAT USE16 ;; FORMAT IP:CS dw isrR, 0 ; 0x00, 0 #DE, Divide Error dw isrR, 0 ; 0x01, 1 #DB, Debug Fault dw isrR, 0 ; 0x02, 2, ---, NMI dw isrR, 0 ; 0x03, 3, #BP, Breakpoint dw isrR, 0 ; 0x04, 4, #OF, INTO detected Overflow dw isrR, 0 ; 0x05, 5, #BR, Bound Range Exceeded dw isrR, 0 ; 0x06, 6, #UD, Invalid Opcode dw isrR, 0 ; 0x07, 7, #NM, Device Not Available dw isrR, 0 ; 0x08, 8, #DF, Double Fault dw isrR, 0 ; 0x09 9, ---, Coprocessor Segment Overrun dw isrR, 0 ; 0x0A, 10, #TS, Invalid TSS dw isrR, 0 ; 0x0B, 11, #NP, Segment Not Present dw isrR, 0 ; 0x0C, 12, #SS, Stack Fault dw isrR, 0 ; 0x0D, 13, #GP, General Protection Fault dw isrR, 0 ; 0x0E, 14, #PF, Page Fault dw isrR, 0 ; 0x0F, 15, ---, Reserved dw isrR, 0 ; 0x10, 16, #MF, Floating Point Fault dw isrR, 0 ; 0x11, 17, #AC, Alignment Check dw isrR, 0 ; 0x12 18, #MC, Machine Check dw isrR, 0 ; 0x13, 19, #XF, SSE Fault isrR: mov eax, 0xDEADBEEF ; Default Real Mode Interrupt Handler out 0x80, eax hlt ;; ######################################################################## ;; SMM Handler ;; ######################################################################## SECTION SMM ABSOLUTE=0x00038000 USE16 rsm ;; ######################################################################## ;; Reset Vector ;; ######################################################################## SECTION RESET ABSOLUTE=0xFFFFFFF0 USE16 jmp far setup
; A203579: Exponential (or binomial) convolution of A000032 (Lucas) with itself, divided by 2. ; 2,2,7,17,57,177,577,1857,6017,19457,62977,203777,659457,2134017,6905857,22347777,72318977,234029057,757334017,2450784257,7930904577,25664946177,83053510657,268766806017,869747654657,2814562533377,9108115685377,29474481504257,95381425750017,308660777517057,998847258034177,3232337626136577 add $0,1 mov $1,1 lpb $0 sub $0,1 mov $2,1 add $3,1 add $2,$3 sub $2,$1 add $1,$3 add $1,$3 sub $2,1 add $3,$1 mov $1,$2 trn $1,3 sub $3,2 lpe add $1,2
// program.cpp // Hidden implementation of program-related classes // Created by Alejandro Castro Garcia on 22 October 2020 /* Licensed under the MIT License Copyright (c) 2020 Faustic Inferno SL Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <nexo/program.hpp> namespace nexo { using std::vector; using std::shared_ptr; int Program::priv_result; int Program::priv_argc; char** Program::priv_argv; vector<shared_ptr<Lifecycle>> Program::lifecycle; class Run_exit {}; void Program::add_lifecycle(std::shared_ptr<Lifecycle>& lf) { lifecycle.push_back(lf); } void Program::cleanup() { // Lifecycle objects might require proper cleanup lifecycle.resize(0); } bool Program::please_quit() { for (auto& lc: lifecycle) { if (!lc->please_quit()) return false; } return true; } void Program::ready() { for (auto& lc: lifecycle) lc->ready(); } void Program::run(int argc, char** argv) { priv_argc = argc; priv_argv = argv; try { event_loop(); } catch(Run_exit) { cleanup(); // Normal termination just unwinds the stack and returns to the caller } } void Program::exit(int ret_value) { priv_result = ret_value; for (auto& lc: lifecycle) lc->quitting(); throw Run_exit(); } } // namespace nexo
#include "common.asm" #ifdef VERTEX ; variables #define lv0 r0 #define lv1 r1 #define lv2 r2 #define lv3 r3 #define normal r4 #define att r5 #define light r6 #define pos r7 #define MAT_DIFFUSE c[uMaterial].x #define MAT_EMISSIVE c[uMaterial].w ; pos = mulQuatPos(uBasis[0], aCoord) mulQuatPos(pos, aCoord, 0) ; vFog = length((uViewPos - pos) * uFogParams.w) applyFog(vFog, pos) ; vPosition = uViewProj * pos mulMat(vPosition, pos, uViewProj) ; vColor = (material.diffuse * aColor.xyz * 2.0 + material.emissive, 1.0) mul tmp, MAT_DIFFUSE, aColor add tmp, tmp, tmp add tmp, tmp, MAT_EMISSIVE mov tmp.w, MAT_EMISSIVE mul tmp, tmp, HALF encodeColor(tmp) ; vTecCoord = (aTexCoord.xyz, 1) mov vTexCoord, aTexCoord mov vTexCoord.w, ONE #else tex t0 applyColor(r0, t0) #endif
; Turbo Patch(es)  1993 Tony Tebby section uq xdef sb_pturbo xref sb_litem include 'dev8_keys_qdos_sms' include 'dev8_keys_sys' include 'dev8_keys_sbasic' include 'dev8_keys_68000' sbpt_name dc.w 13,'BASIC_POINTER' sbpt_code moveq #sms.info,d0 ; get SB vars via SuperBASIC base trap #do.sms2 sbpt_old move.l sys_sbab(a0),a0 lea sb_offs(a0),a0 rts sbpt_repl moveq #sms.info,d0 ; get SB vars via Job 0 trap #do.sms2 ; @@@@@ tst.l d1 ; actually job 0? ; @@@@@ beq.s sbpt_old ; ... yes, use old code move.l sys_jbtb(a0),a0 move.l (a0),a0 lea sb_vars(a0),a0 rts ;+++ ; Patch Turbo TK ; ; a6 c p pointer to SBASIC area ; ; status return standard ;--- sb_pturbo lea sbpt_name+1,a1 ; locate "BASIC_POINTER" jsr sb_litem ble.s sbpt_done lea $200(a1),a0 ; search range movem.l sbpt_code,d1/d2/d3 ; search pattern sbpt_swap swap d1 sbpt_check cmp.l a0,a1 ; end of search? bge.s sbpt_done ; ... yes cmp.w (a1)+,d1 ; match? bne.s sbpt_check ; ... no swap d1 ; try other half cmp.w (a1),d1 ; match? bne.s sbpt_swap ; ... no cmp.l 2(a1),d2 ; 2nd long word? bne.s sbpt_swap ; ... no match cmp.l 6(a1),d3 ; 3nd long word? bne.s sbpt_swap ; ... no match lea sbpt_repl,a0 ; replacement code address move.l a0,(a1) move.w #jmp.l,-(a1) ; and jump sbpt_done moveq #0,d0 rts end
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" //============================================================================== // // Error handling helpers // //============================================================================== namespace { #define error_entry(entry) { entry, #entry } struct ErrorEntry { int code; const char* str; }; struct ErrorEntryComparer { int code; ErrorEntryComparer(int code_) : code(code_) {} bool operator()(const ErrorEntry& e) const { return e.code == code; } }; ////////////////////////////////////////////////////////////////////////// // NCV errors const ErrorEntry ncv_errors [] = { error_entry( NCV_SUCCESS ), error_entry( NCV_UNKNOWN_ERROR ), error_entry( NCV_CUDA_ERROR ), error_entry( NCV_NPP_ERROR ), error_entry( NCV_FILE_ERROR ), error_entry( NCV_NULL_PTR ), error_entry( NCV_INCONSISTENT_INPUT ), error_entry( NCV_TEXTURE_BIND_ERROR ), error_entry( NCV_DIMENSIONS_INVALID ), error_entry( NCV_INVALID_ROI ), error_entry( NCV_INVALID_STEP ), error_entry( NCV_INVALID_SCALE ), error_entry( NCV_INVALID_SCALE ), error_entry( NCV_ALLOCATOR_NOT_INITIALIZED ), error_entry( NCV_ALLOCATOR_BAD_ALLOC ), error_entry( NCV_ALLOCATOR_BAD_DEALLOC ), error_entry( NCV_ALLOCATOR_INSUFFICIENT_CAPACITY ), error_entry( NCV_ALLOCATOR_DEALLOC_ORDER ), error_entry( NCV_ALLOCATOR_BAD_REUSE ), error_entry( NCV_MEM_COPY_ERROR ), error_entry( NCV_MEM_RESIDENCE_ERROR ), error_entry( NCV_MEM_INSUFFICIENT_CAPACITY ), error_entry( NCV_HAAR_INVALID_PIXEL_STEP ), error_entry( NCV_HAAR_TOO_MANY_FEATURES_IN_CLASSIFIER ), error_entry( NCV_HAAR_TOO_MANY_FEATURES_IN_CASCADE ), error_entry( NCV_HAAR_TOO_LARGE_FEATURES ), error_entry( NCV_HAAR_XML_LOADING_EXCEPTION ), error_entry( NCV_NOIMPL_HAAR_TILTED_FEATURES ), error_entry( NCV_WARNING_HAAR_DETECTIONS_VECTOR_OVERFLOW ), error_entry( NPPST_SUCCESS ), error_entry( NPPST_ERROR ), error_entry( NPPST_CUDA_KERNEL_EXECUTION_ERROR ), error_entry( NPPST_NULL_POINTER_ERROR ), error_entry( NPPST_TEXTURE_BIND_ERROR ), error_entry( NPPST_MEMCPY_ERROR ), error_entry( NPPST_MEM_ALLOC_ERR ), error_entry( NPPST_MEMFREE_ERR ), error_entry( NPPST_INVALID_ROI ), error_entry( NPPST_INVALID_STEP ), error_entry( NPPST_INVALID_SCALE ), error_entry( NPPST_MEM_INSUFFICIENT_BUFFER ), error_entry( NPPST_MEM_RESIDENCE_ERROR ), error_entry( NPPST_MEM_INTERNAL_ERROR ) }; const size_t ncv_error_num = sizeof(ncv_errors) / sizeof(ncv_errors[0]); } cv::String cv::cuda::getNcvErrorMessage(int code) { size_t idx = std::find_if(ncv_errors, ncv_errors + ncv_error_num, ErrorEntryComparer(code)) - ncv_errors; const char* msg = (idx != ncv_error_num) ? ncv_errors[idx].str : "Unknown error code"; String str = cv::format("%s [Code = %d]", msg, code); return str; } static void stdDebugOutput(const cv::String &msg) { std::cout << msg.c_str() << std::endl; } static NCVDebugOutputHandler *debugOutputHandler = stdDebugOutput; void ncvDebugOutput(const cv::String &msg) { debugOutputHandler(msg); } void ncvSetDebugOutputHandler(NCVDebugOutputHandler *func) { debugOutputHandler = func; } //============================================================================== // // Memory wrappers and helpers // //============================================================================== Ncv32u alignUp(Ncv32u what, Ncv32u alignment) { Ncv32u alignMask = alignment-1; Ncv32u inverseAlignMask = ~alignMask; Ncv32u res = (what + alignMask) & inverseAlignMask; return res; } void NCVMemPtr::clear() { ptr = NULL; memtype = NCVMemoryTypeNone; } void NCVMemSegment::clear() { begin.clear(); size = 0; } NCVStatus memSegCopyHelper(void *dst, NCVMemoryType dstType, const void *src, NCVMemoryType srcType, size_t sz, cudaStream_t cuStream) { NCVStatus ncvStat; switch (dstType) { case NCVMemoryTypeHostPageable: case NCVMemoryTypeHostPinned: switch (srcType) { case NCVMemoryTypeHostPageable: case NCVMemoryTypeHostPinned: memcpy(dst, src, sz); ncvStat = NCV_SUCCESS; break; case NCVMemoryTypeDevice: if (cuStream != 0) { ncvAssertCUDAReturn(cudaMemcpyAsync(dst, src, sz, cudaMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR); } else { ncvAssertCUDAReturn(cudaMemcpy(dst, src, sz, cudaMemcpyDeviceToHost), NCV_CUDA_ERROR); } ncvStat = NCV_SUCCESS; break; default: ncvStat = NCV_MEM_RESIDENCE_ERROR; } break; case NCVMemoryTypeDevice: switch (srcType) { case NCVMemoryTypeHostPageable: case NCVMemoryTypeHostPinned: if (cuStream != 0) { ncvAssertCUDAReturn(cudaMemcpyAsync(dst, src, sz, cudaMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR); } else { ncvAssertCUDAReturn(cudaMemcpy(dst, src, sz, cudaMemcpyHostToDevice), NCV_CUDA_ERROR); } ncvStat = NCV_SUCCESS; break; case NCVMemoryTypeDevice: if (cuStream != 0) { ncvAssertCUDAReturn(cudaMemcpyAsync(dst, src, sz, cudaMemcpyDeviceToDevice, cuStream), NCV_CUDA_ERROR); } else { ncvAssertCUDAReturn(cudaMemcpy(dst, src, sz, cudaMemcpyDeviceToDevice), NCV_CUDA_ERROR); } ncvStat = NCV_SUCCESS; break; default: ncvStat = NCV_MEM_RESIDENCE_ERROR; } break; default: ncvStat = NCV_MEM_RESIDENCE_ERROR; } return ncvStat; } NCVStatus memSegCopyHelper2D(void *dst, Ncv32u dstPitch, NCVMemoryType dstType, const void *src, Ncv32u srcPitch, NCVMemoryType srcType, Ncv32u widthbytes, Ncv32u height, cudaStream_t cuStream) { NCVStatus ncvStat; switch (dstType) { case NCVMemoryTypeHostPageable: case NCVMemoryTypeHostPinned: switch (srcType) { case NCVMemoryTypeHostPageable: case NCVMemoryTypeHostPinned: for (Ncv32u i=0; i<height; i++) { memcpy((char*)dst + i * dstPitch, (char*)src + i * srcPitch, widthbytes); } ncvStat = NCV_SUCCESS; break; case NCVMemoryTypeDevice: if (cuStream != 0) { ncvAssertCUDAReturn(cudaMemcpy2DAsync(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyDeviceToHost, cuStream), NCV_CUDA_ERROR); } else { ncvAssertCUDAReturn(cudaMemcpy2D(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyDeviceToHost), NCV_CUDA_ERROR); } ncvStat = NCV_SUCCESS; break; default: ncvStat = NCV_MEM_RESIDENCE_ERROR; } break; case NCVMemoryTypeDevice: switch (srcType) { case NCVMemoryTypeHostPageable: case NCVMemoryTypeHostPinned: if (cuStream != 0) { ncvAssertCUDAReturn(cudaMemcpy2DAsync(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyHostToDevice, cuStream), NCV_CUDA_ERROR); } else { ncvAssertCUDAReturn(cudaMemcpy2D(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyHostToDevice), NCV_CUDA_ERROR); } ncvStat = NCV_SUCCESS; break; case NCVMemoryTypeDevice: if (cuStream != 0) { ncvAssertCUDAReturn(cudaMemcpy2DAsync(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyDeviceToDevice, cuStream), NCV_CUDA_ERROR); } else { ncvAssertCUDAReturn(cudaMemcpy2D(dst, dstPitch, src, srcPitch, widthbytes, height, cudaMemcpyDeviceToDevice), NCV_CUDA_ERROR); } ncvStat = NCV_SUCCESS; break; default: ncvStat = NCV_MEM_RESIDENCE_ERROR; } break; default: ncvStat = NCV_MEM_RESIDENCE_ERROR; } return ncvStat; } //=================================================================== // // NCVMemStackAllocator class members implementation // //=================================================================== NCVMemStackAllocator::NCVMemStackAllocator(Ncv32u alignment_) : _memType(NCVMemoryTypeNone), _alignment(alignment_), allocBegin(NULL), begin(NULL), end(NULL), currentSize(0), _maxSize(0), bReusesMemory(false) { NcvBool bProperAlignment = (alignment_ & (alignment_ - 1)) == 0; ncvAssertPrintCheck(bProperAlignment, "NCVMemStackAllocator ctor:: alignment not power of 2"); } NCVMemStackAllocator::NCVMemStackAllocator(NCVMemoryType memT, size_t capacity, Ncv32u alignment_, void *reusePtr) : _memType(memT), _alignment(alignment_), allocBegin(NULL), currentSize(0), _maxSize(0) { NcvBool bProperAlignment = (alignment_ & (alignment_ - 1)) == 0; ncvAssertPrintCheck(bProperAlignment, "NCVMemStackAllocator ctor:: _alignment not power of 2"); ncvAssertPrintCheck(memT != NCVMemoryTypeNone, "NCVMemStackAllocator ctor:: Incorrect allocator type"); allocBegin = NULL; if (reusePtr == NULL && capacity != 0) { bReusesMemory = false; switch (memT) { case NCVMemoryTypeDevice: ncvAssertCUDAReturn(cudaMalloc(&allocBegin, capacity), ); break; case NCVMemoryTypeHostPinned: ncvAssertCUDAReturn(cudaMallocHost(&allocBegin, capacity), ); break; case NCVMemoryTypeHostPageable: allocBegin = (Ncv8u *)malloc(capacity); break; default:; } } else { bReusesMemory = true; allocBegin = (Ncv8u *)reusePtr; } if (capacity == 0) { allocBegin = (Ncv8u *)(0x1); } if (!isCounting()) { begin = allocBegin; end = begin + capacity; } } NCVMemStackAllocator::~NCVMemStackAllocator() { if (allocBegin != NULL) { ncvAssertPrintCheck(currentSize == 0, "NCVMemStackAllocator dtor:: not all objects were deallocated properly, forcing destruction"); if (!bReusesMemory && (allocBegin != (Ncv8u *)(0x1))) { switch (_memType) { case NCVMemoryTypeDevice: ncvAssertCUDAReturn(cudaFree(allocBegin), ); break; case NCVMemoryTypeHostPinned: ncvAssertCUDAReturn(cudaFreeHost(allocBegin), ); break; case NCVMemoryTypeHostPageable: free(allocBegin); break; default:; } } allocBegin = NULL; } } NCVStatus NCVMemStackAllocator::alloc(NCVMemSegment &seg, size_t size) { seg.clear(); ncvAssertReturn(isInitialized(), NCV_ALLOCATOR_BAD_ALLOC); size = alignUp(static_cast<Ncv32u>(size), this->_alignment); this->currentSize += size; this->_maxSize = std::max(this->_maxSize, this->currentSize); if (!isCounting()) { size_t availSize = end - begin; ncvAssertReturn(size <= availSize, NCV_ALLOCATOR_INSUFFICIENT_CAPACITY); } seg.begin.ptr = begin; seg.begin.memtype = this->_memType; seg.size = size; begin += size; return NCV_SUCCESS; } NCVStatus NCVMemStackAllocator::dealloc(NCVMemSegment &seg) { ncvAssertReturn(isInitialized(), NCV_ALLOCATOR_BAD_ALLOC); ncvAssertReturn(seg.begin.memtype == this->_memType, NCV_ALLOCATOR_BAD_DEALLOC); ncvAssertReturn(seg.begin.ptr != NULL || isCounting(), NCV_ALLOCATOR_BAD_DEALLOC); ncvAssertReturn(seg.begin.ptr == begin - seg.size, NCV_ALLOCATOR_DEALLOC_ORDER); currentSize -= seg.size; begin -= seg.size; seg.clear(); ncvAssertReturn(allocBegin <= begin, NCV_ALLOCATOR_BAD_DEALLOC); return NCV_SUCCESS; } NcvBool NCVMemStackAllocator::isInitialized(void) const { return (((this->_alignment & (this->_alignment-1)) == 0) && isCounting()) || this->allocBegin != NULL; } NcvBool NCVMemStackAllocator::isCounting(void) const { return this->_memType == NCVMemoryTypeNone; } NCVMemoryType NCVMemStackAllocator::memType(void) const { return this->_memType; } Ncv32u NCVMemStackAllocator::alignment(void) const { return this->_alignment; } size_t NCVMemStackAllocator::maxSize(void) const { return this->_maxSize; } //=================================================================== // // NCVMemNativeAllocator class members implementation // //=================================================================== NCVMemNativeAllocator::NCVMemNativeAllocator(NCVMemoryType memT, Ncv32u alignment_) : _memType(memT), _alignment(alignment_), currentSize(0), _maxSize(0) { ncvAssertPrintReturn(memT != NCVMemoryTypeNone, "NCVMemNativeAllocator ctor:: counting not permitted for this allocator type", ); } NCVMemNativeAllocator::~NCVMemNativeAllocator() { ncvAssertPrintCheck(currentSize == 0, "NCVMemNativeAllocator dtor:: detected memory leak"); } NCVStatus NCVMemNativeAllocator::alloc(NCVMemSegment &seg, size_t size) { seg.clear(); ncvAssertReturn(isInitialized(), NCV_ALLOCATOR_BAD_ALLOC); switch (this->_memType) { case NCVMemoryTypeDevice: ncvAssertCUDAReturn(cudaMalloc(&seg.begin.ptr, size), NCV_CUDA_ERROR); break; case NCVMemoryTypeHostPinned: ncvAssertCUDAReturn(cudaMallocHost(&seg.begin.ptr, size), NCV_CUDA_ERROR); break; case NCVMemoryTypeHostPageable: seg.begin.ptr = (Ncv8u *)malloc(size); break; default:; } this->currentSize += alignUp(static_cast<Ncv32u>(size), this->_alignment); this->_maxSize = std::max(this->_maxSize, this->currentSize); seg.begin.memtype = this->_memType; seg.size = size; return NCV_SUCCESS; } NCVStatus NCVMemNativeAllocator::dealloc(NCVMemSegment &seg) { ncvAssertReturn(isInitialized(), NCV_ALLOCATOR_BAD_ALLOC); ncvAssertReturn(seg.begin.memtype == this->_memType, NCV_ALLOCATOR_BAD_DEALLOC); ncvAssertReturn(seg.begin.ptr != NULL, NCV_ALLOCATOR_BAD_DEALLOC); ncvAssertReturn(currentSize >= alignUp(static_cast<Ncv32u>(seg.size), this->_alignment), NCV_ALLOCATOR_BAD_DEALLOC); currentSize -= alignUp(static_cast<Ncv32u>(seg.size), this->_alignment); switch (this->_memType) { case NCVMemoryTypeDevice: ncvAssertCUDAReturn(cudaFree(seg.begin.ptr), NCV_CUDA_ERROR); break; case NCVMemoryTypeHostPinned: ncvAssertCUDAReturn(cudaFreeHost(seg.begin.ptr), NCV_CUDA_ERROR); break; case NCVMemoryTypeHostPageable: free(seg.begin.ptr); break; default:; } seg.clear(); return NCV_SUCCESS; } NcvBool NCVMemNativeAllocator::isInitialized(void) const { return (this->_alignment != 0); } NcvBool NCVMemNativeAllocator::isCounting(void) const { return false; } NCVMemoryType NCVMemNativeAllocator::memType(void) const { return this->_memType; } Ncv32u NCVMemNativeAllocator::alignment(void) const { return this->_alignment; } size_t NCVMemNativeAllocator::maxSize(void) const { return this->_maxSize; } //=================================================================== // // Time and timer routines // //=================================================================== typedef struct _NcvTimeMoment NcvTimeMoment; #if defined(_WIN32) || defined(_WIN64) #include BLIK_FAKEWIN_V_windows_h //original-code:<Windows.h> typedef struct _NcvTimeMoment { LONGLONG moment, freq; } NcvTimeMoment; static void _ncvQueryMoment(NcvTimeMoment *t) { QueryPerformanceFrequency((LARGE_INTEGER *)&(t->freq)); QueryPerformanceCounter((LARGE_INTEGER *)&(t->moment)); } double _ncvMomentToMicroseconds(NcvTimeMoment *t) { return 1000000.0 * t->moment / t->freq; } double _ncvMomentsDiffToMicroseconds(NcvTimeMoment *t1, NcvTimeMoment *t2) { return 1000000.0 * 2 * ((t2->moment) - (t1->moment)) / (t1->freq + t2->freq); } double _ncvMomentsDiffToMilliseconds(NcvTimeMoment *t1, NcvTimeMoment *t2) { return 1000.0 * 2 * ((t2->moment) - (t1->moment)) / (t1->freq + t2->freq); } #elif defined(__GNUC__) #include <sys/time.h> typedef struct _NcvTimeMoment { struct timeval tv; struct timezone tz; } NcvTimeMoment; void _ncvQueryMoment(NcvTimeMoment *t) { gettimeofday(& t->tv, & t->tz); } double _ncvMomentToMicroseconds(NcvTimeMoment *t) { return 1000000.0 * t->tv.tv_sec + (double)t->tv.tv_usec; } double _ncvMomentsDiffToMicroseconds(NcvTimeMoment *t1, NcvTimeMoment *t2) { return (((double)t2->tv.tv_sec - (double)t1->tv.tv_sec) * 1000000 + (double)t2->tv.tv_usec - (double)t1->tv.tv_usec); } double _ncvMomentsDiffToMilliseconds(NcvTimeMoment *t1, NcvTimeMoment *t2) { return ((double)t2->tv.tv_sec - (double)t1->tv.tv_sec) * 1000; } #endif //#if defined(_WIN32) || defined(_WIN64) struct _NcvTimer { NcvTimeMoment t1, t2; }; NcvTimer ncvStartTimer(void) { struct _NcvTimer *t; t = (struct _NcvTimer *)malloc(sizeof(struct _NcvTimer)); _ncvQueryMoment(&t->t1); return t; } double ncvEndQueryTimerUs(NcvTimer t) { double res; _ncvQueryMoment(&t->t2); res = _ncvMomentsDiffToMicroseconds(&t->t1, &t->t2); free(t); return res; } double ncvEndQueryTimerMs(NcvTimer t) { double res; _ncvQueryMoment(&t->t2); res = _ncvMomentsDiffToMilliseconds(&t->t1, &t->t2); free(t); return res; } //=================================================================== // // Operations with rectangles // //=================================================================== struct RectConvert { cv::Rect operator()(const NcvRect32u& nr) const { return cv::Rect(nr.x, nr.y, nr.width, nr.height); } NcvRect32u operator()(const cv::Rect& nr) const { NcvRect32u rect; rect.x = nr.x; rect.y = nr.y; rect.width = nr.width; rect.height = nr.height; return rect; } }; static void groupRectangles(std::vector<NcvRect32u> &hypotheses, int groupThreshold, double eps, std::vector<Ncv32u> *weights) { #ifndef HAVE_OPENCV_OBJDETECT (void) hypotheses; (void) groupThreshold; (void) eps; (void) weights; CV_Error(cv::Error::StsNotImplemented, "This functionality requires objdetect module"); #else std::vector<cv::Rect> rects(hypotheses.size()); std::transform(hypotheses.begin(), hypotheses.end(), rects.begin(), RectConvert()); if (weights) { std::vector<int> weights_int; weights_int.assign(weights->begin(), weights->end()); cv::groupRectangles(rects, weights_int, groupThreshold, eps); } else { cv::groupRectangles(rects, groupThreshold, eps); } std::transform(rects.begin(), rects.end(), hypotheses.begin(), RectConvert()); hypotheses.resize(rects.size()); #endif } NCVStatus ncvGroupRectangles_host(NCVVector<NcvRect32u> &hypotheses, Ncv32u &numHypotheses, Ncv32u minNeighbors, Ncv32f intersectEps, NCVVector<Ncv32u> *hypothesesWeights) { ncvAssertReturn(hypotheses.memType() == NCVMemoryTypeHostPageable || hypotheses.memType() == NCVMemoryTypeHostPinned, NCV_MEM_RESIDENCE_ERROR); if (hypothesesWeights != NULL) { ncvAssertReturn(hypothesesWeights->memType() == NCVMemoryTypeHostPageable || hypothesesWeights->memType() == NCVMemoryTypeHostPinned, NCV_MEM_RESIDENCE_ERROR); } if (numHypotheses == 0) { return NCV_SUCCESS; } std::vector<NcvRect32u> rects(numHypotheses); memcpy(&rects[0], hypotheses.ptr(), numHypotheses * sizeof(NcvRect32u)); std::vector<Ncv32u> weights; if (hypothesesWeights != NULL) { groupRectangles(rects, minNeighbors, intersectEps, &weights); } else { groupRectangles(rects, minNeighbors, intersectEps, NULL); } numHypotheses = (Ncv32u)rects.size(); if (numHypotheses > 0) { memcpy(hypotheses.ptr(), &rects[0], numHypotheses * sizeof(NcvRect32u)); } if (hypothesesWeights != NULL) { memcpy(hypothesesWeights->ptr(), &weights[0], numHypotheses * sizeof(Ncv32u)); } return NCV_SUCCESS; } template <class T> static NCVStatus drawRectsWrapperHost(T *h_dst, Ncv32u dstStride, Ncv32u dstWidth, Ncv32u dstHeight, NcvRect32u *h_rects, Ncv32u numRects, T color) { ncvAssertReturn(h_dst != NULL && h_rects != NULL, NCV_NULL_PTR); ncvAssertReturn(dstWidth > 0 && dstHeight > 0, NCV_DIMENSIONS_INVALID); ncvAssertReturn(dstStride >= dstWidth, NCV_INVALID_STEP); ncvAssertReturn(numRects != 0, NCV_SUCCESS); ncvAssertReturn(numRects <= dstWidth * dstHeight, NCV_DIMENSIONS_INVALID); for (Ncv32u i=0; i<numRects; i++) { NcvRect32u rect = h_rects[i]; if (rect.x < dstWidth) { for (Ncv32u each=rect.y; each<rect.y+rect.height && each<dstHeight; each++) { h_dst[each*dstStride+rect.x] = color; } } if (rect.x+rect.width-1 < dstWidth) { for (Ncv32u each=rect.y; each<rect.y+rect.height && each<dstHeight; each++) { h_dst[each*dstStride+rect.x+rect.width-1] = color; } } if (rect.y < dstHeight) { for (Ncv32u j=rect.x; j<rect.x+rect.width && j<dstWidth; j++) { h_dst[rect.y*dstStride+j] = color; } } if (rect.y + rect.height - 1 < dstHeight) { for (Ncv32u j=rect.x; j<rect.x+rect.width && j<dstWidth; j++) { h_dst[(rect.y+rect.height-1)*dstStride+j] = color; } } } return NCV_SUCCESS; } NCVStatus ncvDrawRects_8u_host(Ncv8u *h_dst, Ncv32u dstStride, Ncv32u dstWidth, Ncv32u dstHeight, NcvRect32u *h_rects, Ncv32u numRects, Ncv8u color) { return drawRectsWrapperHost(h_dst, dstStride, dstWidth, dstHeight, h_rects, numRects, color); } NCVStatus ncvDrawRects_32u_host(Ncv32u *h_dst, Ncv32u dstStride, Ncv32u dstWidth, Ncv32u dstHeight, NcvRect32u *h_rects, Ncv32u numRects, Ncv32u color) { return drawRectsWrapperHost(h_dst, dstStride, dstWidth, dstHeight, h_rects, numRects, color); }
ZoneMons1: db $1E db 21,CHANSEY db 29,MILTANK db 22,EXEGGCUTE db 21,TAUROS db 32,NIDORINA db 19,CUBONE db 26,EXEGGCUTE db 24,MAROWAK db 40,CHANSEY db 15,SCYTHER db $00
//===--- PthreadLockChecker.cpp - Check for locking problems ---*- C++ -*--===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This defines PthreadLockChecker, a simple lock -> unlock checker. // Also handles XNU locks, which behave similarly enough to share code. // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "llvm/ADT/ImmutableList.h" using namespace clang; using namespace ento; namespace { class PthreadLockChecker : public Checker< check::PostStmt<CallExpr> > { mutable OwningPtr<BugType> BT_doublelock; mutable OwningPtr<BugType> BT_lor; enum LockingSemantics { NotApplicable = 0, PthreadSemantics, XNUSemantics }; public: void checkPostStmt(const CallExpr *CE, CheckerContext &C) const; void AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock, bool isTryLock, enum LockingSemantics semantics) const; void ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const; }; } // end anonymous namespace // GDM Entry for tracking lock state. REGISTER_LIST_WITH_PROGRAMSTATE(LockSet, const MemRegion *) void PthreadLockChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { ProgramStateRef state = C.getState(); const LocationContext *LCtx = C.getLocationContext(); StringRef FName = C.getCalleeName(CE); if (FName.empty()) return; if (CE->getNumArgs() != 1) return; if (FName == "pthread_mutex_lock" || FName == "pthread_rwlock_rdlock" || FName == "pthread_rwlock_wrlock") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), false, PthreadSemantics); else if (FName == "lck_mtx_lock" || FName == "lck_rw_lock_exclusive" || FName == "lck_rw_lock_shared") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), false, XNUSemantics); else if (FName == "pthread_mutex_trylock" || FName == "pthread_rwlock_tryrdlock" || FName == "pthread_rwlock_tryrwlock") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), true, PthreadSemantics); else if (FName == "lck_mtx_try_lock" || FName == "lck_rw_try_lock_exclusive" || FName == "lck_rw_try_lock_shared") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), true, XNUSemantics); else if (FName == "pthread_mutex_unlock" || FName == "pthread_rwlock_unlock" || FName == "lck_mtx_unlock" || FName == "lck_rw_done") ReleaseLock(C, CE, state->getSVal(CE->getArg(0), LCtx)); } void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock, bool isTryLock, enum LockingSemantics semantics) const { const MemRegion *lockR = lock.getAsRegion(); if (!lockR) return; ProgramStateRef state = C.getState(); SVal X = state->getSVal(CE, C.getLocationContext()); if (X.isUnknownOrUndef()) return; DefinedSVal retVal = X.castAs<DefinedSVal>(); if (state->contains<LockSet>(lockR)) { if (!BT_doublelock) BT_doublelock.reset(new BugType("Double locking", "Lock checker")); ExplodedNode *N = C.generateSink(); if (!N) return; BugReport *report = new BugReport(*BT_doublelock, "This lock has already " "been acquired", N); report->addRange(CE->getArg(0)->getSourceRange()); C.emitReport(report); return; } ProgramStateRef lockSucc = state; if (isTryLock) { // Bifurcate the state, and allow a mode where the lock acquisition fails. ProgramStateRef lockFail; switch (semantics) { case PthreadSemantics: llvm::tie(lockFail, lockSucc) = state->assume(retVal); break; case XNUSemantics: llvm::tie(lockSucc, lockFail) = state->assume(retVal); break; default: llvm_unreachable("Unknown tryLock locking semantics"); } assert(lockFail && lockSucc); C.addTransition(lockFail); } else if (semantics == PthreadSemantics) { // Assume that the return value was 0. lockSucc = state->assume(retVal, false); assert(lockSucc); } else { // XNU locking semantics return void on non-try locks assert((semantics == XNUSemantics) && "Unknown locking semantics"); lockSucc = state; } // Record that the lock was acquired. lockSucc = lockSucc->add<LockSet>(lockR); C.addTransition(lockSucc); } void PthreadLockChecker::ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const { const MemRegion *lockR = lock.getAsRegion(); if (!lockR) return; ProgramStateRef state = C.getState(); LockSetTy LS = state->get<LockSet>(); // FIXME: Better analysis requires IPA for wrappers. // FIXME: check for double unlocks if (LS.isEmpty()) return; const MemRegion *firstLockR = LS.getHead(); if (firstLockR != lockR) { if (!BT_lor) BT_lor.reset(new BugType("Lock order reversal", "Lock checker")); ExplodedNode *N = C.generateSink(); if (!N) return; BugReport *report = new BugReport(*BT_lor, "This was not the most " "recently acquired lock. " "Possible lock order " "reversal", N); report->addRange(CE->getArg(0)->getSourceRange()); C.emitReport(report); return; } // Record that the lock was released. state = state->set<LockSet>(LS.getTail()); C.addTransition(state); } void ento::registerPthreadLockChecker(CheckerManager &mgr) { mgr.registerChecker<PthreadLockChecker>(); }
copyright zengfr site:http://github.com/zengfr/romhack 006080 tst.b ($53,A6) 006084 ble $60e0 [123p+ 53, enemy+53] 0060E2 tst.b ($53,A6) 0060E6 ble $6146 [123p+ 53] 009C0C tst.b ($53,A6) 009C10 bge $9c20 [123p+ 53] 01302C move.b ($a,A0), ($53,A6) 013032 tst.w (A0) [123p+ 53, enemy+53, etc+53, item+53] 014136 move.b ($53,A0), D0 01413A move.w ($8,A0), D1 [123p+ 53] 014146 clr.b ($53,A0) 01414A move.w ($3c,A0), D0 [123p+ 53] 01416C move.b D0, ($53,A0) 014170 move.w D1, ($8,A0) [123p+ 53] 0142BE tst.b ($53,A0) 0142C2 beq $142d8 [123p+ 53, enemy+53, item+53] 01439C bset #$7, ($53,A0) 0143A2 btst #$5, ($25,A0) [123p+ 53, enemy+53, item+53] 014494 tst.b ($53,A0) 014498 beq $144ae [123p+ 53, enemy+53, etc+53, item+53] 01463E bset #$7, ($53,A0) 014644 btst #$5, ($25,A0) [123p+ 53, enemy+53, item+53] 014EE8 tst.b ($53,A0) [123p+ 56, enemy+56, item+56] 014EEC beq $14f06 [123p+ 53, enemy+53, item+53] 014EF0 btst #$7, ($53,A0) 014EF6 bne $14f92 [123p+ 53, enemy+53] 0192DE tst.b ($53,A6) 0192E2 beq $1931e [123p+ 53] 01A020 tst.b ($53,A6) 01A024 beq $1a064 [123p+ 53] 092E64 tst.b ($53,A6) 092E68 beq $92e76 [123p+ 53, enemy+53] copyright zengfr site:http://github.com/zengfr/romhack
; Arquivo: LCDletraGrupo.nasm ; Curso: Elementos de Sistemas ; Criado por: Rafael Corsi ; Data: 28/3/2018 ; ; Escreva no LCD a letra do grupo de vocês ; - Valide no hardawre ; - Bata uma foto! leaw $255, %A movw %A, %D leaw $17053, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17054, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $17055, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $17073, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17074, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $17075, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $17092, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17093, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17094, %A movw %D, (%A) leaw $65532, %A movw %A, %D leaw $17095, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $17112, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17113, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17114, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17115, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $17116, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $17132, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17133, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17134, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17135, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $17136, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $17152, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17153, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17154, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17155, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $17156, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $17172, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17173, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17174, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17175, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $17176, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $17191, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17192, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17193, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17194, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17195, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $17196, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $17211, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17212, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17213, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17214, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17215, %A movw %D, (%A) leaw $65528, %A movw %A, %D leaw $17216, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $17231, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17232, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17233, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17234, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17235, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $17236, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $17251, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17252, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $17253, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $17254, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17255, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17256, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $17271, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17272, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $17273, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $17274, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17275, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17276, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $17277, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $17291, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17292, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $17293, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $17294, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17295, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17296, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $17297, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $17311, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17312, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $17313, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $17314, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17315, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17316, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $17317, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $17331, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17332, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17335, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17336, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $17337, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $17351, %A movw %D, (%A) leaw $65532, %A movw %A, %D leaw $17352, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $17355, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17356, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $17357, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $17371, %A movw %D, (%A) leaw $65528, %A movw %A, %D leaw $17372, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $17375, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17376, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $17377, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17391, %A movw %D, (%A) leaw $65520, %A movw %A, %D leaw $17392, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $17395, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17396, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $17397, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $17410, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17411, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $17412, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17415, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17416, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $17417, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $17430, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17431, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $17432, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $17435, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17436, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $17437, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $17450, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17451, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $17452, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $17455, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17456, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $17457, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $17470, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17471, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $17472, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $17475, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17476, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $17477, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $17490, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17491, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $17492, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $17495, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17496, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $17497, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $17510, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17511, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $17512, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $17515, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17516, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $17517, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $17530, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17531, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $17532, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $17535, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17536, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $17537, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $17550, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17551, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $17552, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $17555, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17556, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $17557, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $17570, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17571, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $17572, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $17575, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17576, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $17577, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $17590, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17591, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $17592, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $17595, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17596, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $17597, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $17610, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17611, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $17612, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $17615, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17616, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $17617, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $17630, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17631, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $17632, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $17635, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17636, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $17637, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $17650, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17651, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $17652, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $17655, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17656, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $17657, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $17670, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17671, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $17672, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $17675, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17676, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $17677, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $17690, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17691, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $17692, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $17695, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17696, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $17697, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $17710, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17711, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $17712, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $17715, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17716, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $17717, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $17730, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17731, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $17732, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $17735, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17736, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $17737, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17750, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17751, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $17752, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $17755, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17756, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $17757, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17770, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17771, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $17772, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17776, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $17777, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17790, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17791, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $17792, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $17796, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $17797, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17810, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17811, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $17812, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $17816, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $17817, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17830, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17831, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $17832, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $17836, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $17837, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17850, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17851, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $17852, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17856, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $17857, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17870, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17871, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $17872, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $17876, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $17877, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17890, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17891, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $17892, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17910, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17911, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $17912, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17930, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17931, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $17932, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17950, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17951, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $17952, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17970, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17971, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $17972, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $17990, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $17991, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $17992, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $18010, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18011, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $18012, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $18030, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18031, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $18032, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $18050, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18051, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $18052, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $18070, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18071, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $18072, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $18090, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18091, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $18092, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $18110, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18111, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $18112, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $18130, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18131, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $18132, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $18150, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18151, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $18152, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $18170, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18171, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $18172, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $18190, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18191, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $18192, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $18210, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18211, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $18212, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $18230, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18231, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $18232, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $18250, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18251, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $18252, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $18270, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18271, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $18272, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $18290, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18291, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $18292, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $18310, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18311, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $18312, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $18330, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18331, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $18332, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $18350, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18351, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $18352, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $18370, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18371, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $18372, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18391, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $18392, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $18411, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $18412, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $18431, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $18432, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $18451, %A movw %D, (%A) leaw $65520, %A movw %A, %D leaw $18452, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $18471, %A movw %D, (%A) leaw $65528, %A movw %A, %D leaw $18472, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $18491, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $18492, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $18511, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18512, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $18513, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $18531, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18532, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $18533, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $18551, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18552, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $18553, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $18554, %A movw %D, (%A) leaw $65520, %A movw %A, %D leaw $18555, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $18571, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18572, %A movw %D, (%A) leaw $65532, %A movw %A, %D leaw $18573, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $18574, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $18575, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18592, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18593, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18594, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18595, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $18612, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18613, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18614, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18615, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $18616, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $18632, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18633, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18634, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18635, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $18636, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $18652, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18653, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18654, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18655, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $18656, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $18672, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18673, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18674, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18675, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $18676, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $18692, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18693, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18694, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18695, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $18696, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $18711, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18712, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18713, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18714, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18715, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $18716, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $18731, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18732, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18733, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18734, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18735, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $18736, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $18751, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18752, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18753, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18754, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18755, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $18771, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18772, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $18773, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $18774, %A movw %D, (%A) leaw $65532, %A movw %A, %D leaw $18775, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $18791, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18792, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $18793, %A movw %D, (%A) leaw $32736, %A movw %A, %D leaw $18795, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $18811, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18812, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $18813, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $18831, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $18832, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18851, %A movw %D, (%A) leaw $65528, %A movw %A, %D leaw $18852, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $18870, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18871, %A movw %D, (%A) leaw $65520, %A movw %A, %D leaw $18872, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $18890, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18891, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $18892, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $18910, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18911, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $18912, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $18930, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18931, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $18932, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $18950, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18951, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $18952, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $18970, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18971, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $18972, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $18990, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $18991, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $18992, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $19010, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19011, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $19012, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $19030, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19031, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $19032, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $19050, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19051, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $19052, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $19070, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19071, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $19072, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $19090, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19091, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $19092, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $19110, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19111, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $19112, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $19130, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19131, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $19132, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $19150, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19151, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19152, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19170, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19171, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19172, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $19189, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19190, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19191, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19192, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $19209, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19210, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19211, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $19229, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19230, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19231, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $19249, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19250, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19251, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $19269, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19270, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19271, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $19289, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19290, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19291, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19309, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19310, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19311, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19329, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19330, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19331, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19349, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19350, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19351, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19369, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19370, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19371, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19389, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19390, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19391, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $19409, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19410, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19411, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $19416, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $19417, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $19429, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19430, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19431, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $19436, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $19437, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $19449, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19450, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19451, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $19456, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $19457, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $19469, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19470, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19471, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $19476, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $19477, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $19489, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19490, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19491, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $19496, %A movw %D, (%A) leaw $65520, %A movw %A, %D leaw $19497, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $19509, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19510, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19511, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $19516, %A movw %D, (%A) leaw $65528, %A movw %A, %D leaw $19517, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $19529, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19530, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19531, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $19536, %A movw %D, (%A) leaw $65532, %A movw %A, %D leaw $19537, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $19549, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19550, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19551, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $19556, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19557, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19569, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19570, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19571, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $19576, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19577, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19589, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19590, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19591, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $19596, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19597, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19609, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19610, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19611, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $19616, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19617, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19629, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19630, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19631, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $19636, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19637, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19638, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19649, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19650, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19651, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $19656, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19657, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19658, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19669, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19670, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19671, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $19676, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19677, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19678, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $19689, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19690, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19691, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19696, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19697, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19698, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $19709, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19710, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19711, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19716, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19717, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19718, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $19729, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19730, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19731, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19732, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $19735, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19736, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19737, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19738, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $19749, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19750, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19751, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19752, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $19755, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19756, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19757, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19758, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $19769, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19770, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19771, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19772, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $19775, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19776, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19777, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19778, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19790, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19791, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19792, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $19795, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19796, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19797, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19798, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19810, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19811, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $19812, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $19815, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19816, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19817, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19818, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $19830, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19831, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $19832, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $19835, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19836, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19837, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $19838, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $19850, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19851, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $19852, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19855, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19856, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19857, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $19870, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19871, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $19872, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19875, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19876, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19877, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $19890, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19891, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $19892, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $19895, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19896, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19897, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $19910, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19911, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $19912, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $19915, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19916, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19917, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $19930, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19931, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $19932, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $19935, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19936, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $19937, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $19950, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19951, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $19952, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $19955, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19956, %A movw %D, (%A) leaw $65532, %A movw %A, %D leaw $19957, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $19970, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19971, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $19972, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $19975, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19976, %A movw %D, (%A) leaw $65532, %A movw %A, %D leaw $19977, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $19990, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19991, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $19992, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $19995, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $19996, %A movw %D, (%A) leaw $65528, %A movw %A, %D leaw $19997, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $20010, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20011, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $20012, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $20015, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20016, %A movw %D, (%A) leaw $65520, %A movw %A, %D leaw $20017, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $20030, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20031, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $20032, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $20035, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20036, %A movw %D, (%A) leaw $65520, %A movw %A, %D leaw $20037, %A movw %D, (%A) leaw $127, %A movw %A, %D leaw $20050, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20051, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $20052, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $20055, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20056, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $20057, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $20070, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20071, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $20072, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $20075, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20076, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $20077, %A movw %D, (%A) leaw $31, %A movw %A, %D leaw $20090, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20091, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $20092, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $20095, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20096, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $20097, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $20110, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20111, %A movw %D, (%A) leaw $65520, %A movw %A, %D leaw $20112, %A movw %D, (%A) leaw $2047, %A movw %A, %D leaw $20115, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20116, %A movw %D, (%A) leaw $65280, %A movw %A, %D leaw $20117, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $20130, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20131, %A movw %D, (%A) leaw $65532, %A movw %A, %D leaw $20132, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $20135, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20136, %A movw %D, (%A) leaw $65024, %A movw %A, %D leaw $20137, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $20150, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20151, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $20152, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $20155, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20156, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $20157, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $20171, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20172, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $20173, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $20175, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20176, %A movw %D, (%A) leaw $63488, %A movw %A, %D leaw $20177, %A movw %D, (%A) leaw $16383, %A movw %A, %D leaw $20191, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20192, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $20193, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $20194, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20195, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20196, %A movw %D, (%A) leaw $57344, %A movw %A, %D leaw $20197, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $20211, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20212, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $20213, %A movw %D, (%A) leaw $7, %A movw %A, %D leaw $20214, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20215, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20216, %A movw %D, (%A) leaw $49152, %A movw %A, %D leaw $20217, %A movw %D, (%A) leaw $1023, %A movw %A, %D leaw $20231, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20232, %A movw %D, (%A) leaw $65472, %A movw %A, %D leaw $20233, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $20234, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20235, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20236, %A movw %D, (%A) leaw $255, %A movw %A, %D leaw $20251, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20252, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20253, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20254, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20255, %A movw %D, (%A) leaw $65534, %A movw %A, %D leaw $20256, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $20271, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20272, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20273, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20274, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20275, %A movw %D, (%A) leaw $65528, %A movw %A, %D leaw $20276, %A movw %D, (%A) leaw $15, %A movw %A, %D leaw $20291, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20292, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20293, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20294, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20295, %A movw %D, (%A) leaw $65504, %A movw %A, %D leaw $20296, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $20311, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20312, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20313, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20314, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20315, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $20316, %A movw %D, (%A) leaw $32767, %A movw %A, %D leaw $20332, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20333, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20334, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20335, %A movw %D, (%A) leaw $64512, %A movw %A, %D leaw $20336, %A movw %D, (%A) leaw $8191, %A movw %A, %D leaw $20352, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20353, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20354, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20355, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $20356, %A movw %D, (%A) leaw $511, %A movw %A, %D leaw $20372, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20373, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20374, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20375, %A movw %D, (%A) leaw $32768, %A movw %A, %D leaw $20376, %A movw %D, (%A) leaw $63, %A movw %A, %D leaw $20392, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20393, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20394, %A movw %D, (%A) leaw $65528, %A movw %A, %D leaw $20395, %A movw %D, (%A) leaw $3, %A movw %A, %D leaw $20412, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20413, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20414, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $20415, %A movw %D, (%A) leaw $4095, %A movw %A, %D leaw $20433, %A movw %D, (%A) leaw $65535, %A movw %A, %D leaw $20434, %A movw %D, (%A) leaw $61440, %A movw %A, %D leaw $20435, %A movw %D, (%A) leaw $1, %A movw %A, %D leaw $20453, %A movw %D, (%A) leaw $65408, %A movw %A, %D leaw $20454, %A movw %D, (%A)
; A304828: a(n) = 344*7^n/21 - 128/3 (n>=1). ; 72,760,5576,39288,275272,1927160,13490376,94432888,661030472,4627213560,32390495176,226733466488,1587134265672,11109939859960,77769579019976,544387053140088,3810709371980872,26674965603866360,186724759227064776,1307073314589453688,9149513202126176072,64046592414883232760,448326146904182629576,3138283028329278407288,21967981198304948851272,153775868388134641959160,1076431078716942493714376,7535017551018597456000888,52745122857130182192006472,369215859999911275344045560,2584511019999378927408319176,18091577139995652491858234488,126641039979969567443007641672,886487279859786972101053491960,6205410959018508804707374443976,43437876713129561632951621108088,304065136991906931430661347756872,2128455958943348520014629434298360,14899191712603439640102406040088776,104294341988224077480716842280621688,730060393917568542365017895964352072 mov $2,7 pow $2,$0 mov $0,$2 div $0,6 mul $0,688 add $0,72
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_RockGolem_Character_BP_Summoned_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass RockGolem_Character_BP_Summoned.RockGolem_Character_BP_Summoned_C // 0x0000 (0x2455 - 0x2455) class ARockGolem_Character_BP_Summoned_C : public ARockGolem_Character_BP_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass RockGolem_Character_BP_Summoned.RockGolem_Character_BP_Summoned_C"); return ptr; } void UserConstructionScript(); void ExecuteUbergraph_RockGolem_Character_BP_Summoned(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
; non-volatile statuses SLP EQU %111 ; sleep counter PSN EQU 3 BRN EQU 4 FRZ EQU 5 PAR EQU 6 ; volatile statuses 1 STORING_ENERGY EQU 0 ; Bide THRASHING_ABOUT EQU 1 ; e.g. Thrash ATTACKING_MULTIPLE_TIMES EQU 2 ; e.g. Double Kick, Fury Attack FLINCHED EQU 3 CHARGING_UP EQU 4 ; e.g. Solar Beam, Fly USING_TRAPPING_MOVE EQU 5 ; e.g. Wrap INVULNERABLE EQU 6 ; charging up Fly/Dig CONFUSED EQU 7 ; volatile statuses 2 USING_X_ACCURACY EQU 0 PROTECTED_BY_MIST EQU 1 GETTING_PUMPED EQU 2 ; Focus Energy ; EQU 3 ; unused HAS_SUBSTITUTE_UP EQU 4 NEEDS_TO_RECHARGE EQU 5 ; Hyper Beam USING_RAGE EQU 6 SEEDED EQU 7 ; volatile statuses 3 BADLY_POISONED EQU 0 HAS_LIGHT_SCREEN_UP EQU 1 HAS_REFLECT_UP EQU 2 TRANSFORMED EQU 3
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/renderer/content_watcher.h" #include "content/public/renderer/render_view.h" #include "content/public/renderer/render_view_visitor.h" #include "extensions/common/extension_messages.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebScriptBindings.h" #include "third_party/WebKit/public/web/WebView.h" namespace extensions { using blink::WebString; using blink::WebVector; using blink::WebView; ContentWatcher::ContentWatcher() {} ContentWatcher::~ContentWatcher() {} void ContentWatcher::OnWatchPages( const std::vector<std::string>& new_css_selectors_utf8) { blink::WebVector<blink::WebString> new_css_selectors( new_css_selectors_utf8.size()); bool changed = new_css_selectors.size() != css_selectors_.size(); for (size_t i = 0; i < new_css_selectors.size(); ++i) { new_css_selectors[i] = blink::WebString::fromUTF8(new_css_selectors_utf8[i]); if (!changed && new_css_selectors[i] != css_selectors_[i]) changed = true; } if (!changed) return; css_selectors_.swap(new_css_selectors); // Tell each frame's document about the new set of watched selectors. These // will trigger calls to DidMatchCSS after Blink has a chance to apply the new // style, which will in turn notify the browser about the changes. struct WatchSelectors : public content::RenderViewVisitor { explicit WatchSelectors(const WebVector<WebString>& css_selectors) : css_selectors_(css_selectors) {} bool Visit(content::RenderView* view) override { for (blink::WebFrame* frame = view->GetWebView()->mainFrame(); frame; frame = frame->traverseNext(/*wrap=*/false)) frame->document().watchCSSSelectors(css_selectors_); return true; // Continue visiting. } const WebVector<WebString>& css_selectors_; }; WatchSelectors visitor(css_selectors_); content::RenderView::ForEach(&visitor); } void ContentWatcher::DidCreateDocumentElement(blink::WebFrame* frame) { frame->document().watchCSSSelectors(css_selectors_); } void ContentWatcher::DidMatchCSS( blink::WebFrame* frame, const WebVector<WebString>& newly_matching_selectors, const WebVector<WebString>& stopped_matching_selectors) { std::set<std::string>& frame_selectors = matching_selectors_[frame]; for (size_t i = 0; i < stopped_matching_selectors.size(); ++i) frame_selectors.erase(stopped_matching_selectors[i].utf8()); for (size_t i = 0; i < newly_matching_selectors.size(); ++i) frame_selectors.insert(newly_matching_selectors[i].utf8()); if (frame_selectors.empty()) matching_selectors_.erase(frame); NotifyBrowserOfChange(frame); } void ContentWatcher::NotifyBrowserOfChange( blink::WebFrame* changed_frame) const { blink::WebFrame* const top_frame = changed_frame->top(); const blink::WebSecurityOrigin top_origin = top_frame->document().securityOrigin(); // Want to aggregate matched selectors from all frames where an // extension with access to top_origin could run on the frame. if (!top_origin.canAccess(changed_frame->document().securityOrigin())) { // If the changed frame can't be accessed by the top frame, then // no change in it could affect the set of selectors we'd send back. return; } std::set<base::StringPiece> transitive_selectors; for (blink::WebFrame* frame = top_frame; frame; frame = frame->traverseNext(/*wrap=*/false)) { if (top_origin.canAccess(frame->document().securityOrigin())) { std::map<blink::WebFrame*, std::set<std::string> >::const_iterator frame_selectors = matching_selectors_.find(frame); if (frame_selectors != matching_selectors_.end()) { transitive_selectors.insert(frame_selectors->second.begin(), frame_selectors->second.end()); } } } std::vector<std::string> selector_strings; for (std::set<base::StringPiece>::const_iterator it = transitive_selectors.begin(); it != transitive_selectors.end(); ++it) selector_strings.push_back(it->as_string()); content::RenderView* view = content::RenderView::FromWebView(top_frame->view()); view->Send(new ExtensionHostMsg_OnWatchedPageChange(view->GetRoutingID(), selector_strings)); } } // namespace extensions
.global s_prepare_buffers s_prepare_buffers: push %r8 push %r9 push %rbp push %rcx push %rdi push %rsi lea addresses_WT_ht+0x90e9, %rsi lea addresses_WC_ht+0x11c89, %rdi nop nop nop nop nop lfence mov $120, %rcx rep movsq nop nop nop nop and %r9, %r9 lea addresses_WC_ht+0x13885, %r8 nop add $56520, %rbp mov $0x6162636465666768, %rcx movq %rcx, (%r8) nop xor %r9, %r9 lea addresses_normal_ht+0x4df1, %rsi nop nop nop xor %rdi, %rdi movl $0x61626364, (%rsi) xor $3402, %rcx pop %rsi pop %rdi pop %rcx pop %rbp pop %r9 pop %r8 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r14 push %r15 push %r8 push %rax push %rcx // Store lea addresses_PSE+0x99b7, %r15 clflush (%r15) nop inc %r14 movl $0x51525354, (%r15) dec %r8 // Store lea addresses_PSE+0x156a5, %r13 nop nop nop nop inc %rax movw $0x5152, (%r13) nop nop nop inc %r8 // Store lea addresses_normal+0x16489, %r10 nop nop nop nop inc %rcx movl $0x51525354, (%r10) nop add $7767, %rcx // Store lea addresses_D+0x17c51, %r13 nop add %r10, %r10 movl $0x51525354, (%r13) cmp %r14, %r14 // Store lea addresses_WT+0x15fe9, %r8 nop nop nop and $7597, %rcx movl $0x51525354, (%r8) nop nop nop nop and %r10, %r10 // Store lea addresses_WT+0x7f89, %r14 nop nop add %r10, %r10 mov $0x5152535455565758, %r13 movq %r13, %xmm2 movups %xmm2, (%r14) nop nop nop nop sub %r8, %r8 // Faulty Load lea addresses_normal+0x16489, %r13 nop nop nop nop nop add %rax, %rax mov (%r13), %ecx lea oracles, %r15 and $0xff, %rcx shlq $12, %rcx mov (%r15,%rcx,1), %rcx pop %rcx pop %rax pop %r8 pop %r15 pop %r14 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_normal', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 2}} {'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_normal', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_D', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 5, 'type': 'addresses_WT', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_WT', 'AVXalign': False, 'size': 16}} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_normal', 'AVXalign': True, 'size': 4}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 5, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 4}} {'54': 9344} 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 */
#include "motis/module/clog_redirect.h" #include <iostream> namespace motis::module { clog_redirect::clog_redirect(char const* log_file_path) : backup_clog_{std::clog.rdbuf()} { if (!enabled_) { return; } sink_.exceptions(std::ios_base::badbit | std::ios_base::failbit); sink_.open(log_file_path, std::ios_base::app); std::clog.rdbuf(sink_.rdbuf()); } clog_redirect::~clog_redirect() { if (enabled_) { std::clog.rdbuf(backup_clog_); } } void clog_redirect::set_enabled(bool const enabled) { enabled_ = enabled; } bool clog_redirect::enabled_ = true; } // namespace motis::module
; BEGIN_LEGAL ; Intel Open Source License ; ; Copyright (c) 2002-2017 Intel Corporation. All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are ; met: ; ; Redistributions of source code must retain the above copyright notice, ; this list of conditions and the following disclaimer. Redistributions ; in binary form must reproduce the above copyright notice, this list of ; conditions and the following disclaimer in the documentation and/or ; other materials provided with the distribution. Neither the name of ; the Intel Corporation nor the names of its contributors may be used to ; endorse or promote products derived from this software without ; specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ; ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ; END_LEGAL PUBLIC ZeroAppFlags_asm .686 .model flat, c .code ZeroAppFlags_asm PROC pushfd pop eax and eax, 0fffff326H push eax popfd ret ZeroAppFlags_asm ENDP end
; A048479: a(n) = T(7,n), array T given by A048472. ; 1,9,33,97,257,641,1537,3585,8193,18433,40961,90113,196609,425985,917505,1966081,4194305,8912897,18874369,39845889,83886081,176160769,369098753,771751937,1610612737,3355443201,6979321857,14495514625,30064771073,62277025793,128849018881,266287972353,549755813889,1133871366145,2336462209025,4810363371521,9895604649985,20340965113857,41781441855489,85761906966529,175921860444161,360639813910529,738871813865473,1512927999819777,3096224743817217,6333186975989761 mov $1,2 pow $1,$0 mul $1,4 mul $1,$0 add $1,1
/** \file "AST/PRS.cc" PRS-related syntax class method definitions. $Id: PRS.cc,v 1.44 2011/02/08 02:06:44 fang Exp $ This file used to be the following before it was renamed: Id: art_parser_prs.cc,v 1.21.10.1 2005/12/11 00:45:09 fang Exp */ #ifndef __HAC_AST_PRS_CC__ #define __HAC_AST_PRS_CC__ #define ENABLE_STACKTRACE 0 #include <iostream> #include <iterator> #include <algorithm> #include <functional> #include "AST/PRS.hh" #include "AST/reference.hh" // for id_expr #include "AST/expr_list.hh" // for attributes #include "AST/attribute.hh" #include "AST/range.hh" #include "AST/range_list.hh" #include "AST/token.hh" #include "AST/token_char.hh" #include "AST/token_string.hh" #include "AST/node_list.tcc" #include "AST/parse_context.hh" #include "Object/def/process_definition.hh" #include "Object/expr/pint_const.hh" #include "Object/expr/pbool_expr.hh" #include "Object/expr/param_expr.hh" #include "Object/expr/dynamic_param_expr_list.hh" #include "Object/expr/data_expr.hh" #include "Object/expr/pstring_expr.hh" #include "Object/expr/meta_range_expr.hh" #include "Object/expr/meta_index_list.hh" #include "Object/lang/PRS.hh" #include "Object/lang/PRS_attribute_registry.hh" #include "Object/lang/PRS_literal_attribute_registry.hh" #include "Object/lang/PRS_macro_registry.hh" #include "Object/inst/pint_value_collection.hh" #include "Object/traits/bool_traits.hh" #include "Object/ref/meta_instance_reference_base.hh" #include "Object/ref/meta_instance_reference_subtypes.hh" // for conversion #include "Object/ref/nonmeta_instance_reference_subtypes.hh" #include "Object/ref/simple_meta_instance_reference.hh" // for conversion #include "Object/ref/meta_reference_union.hh" #include "Object/module.hh" #include "Object/ref/simple_meta_dummy_reference.hh" #include "Object/ref/references_fwd.hh" #include "Object/traits/node_traits.hh" #include "common/ICE.hh" #include "common/TODO.hh" #include "util/what.hh" #include "util/stacktrace.hh" #include "util/memory/count_ptr.tcc" #define CONSTRUCTOR_INLINE #define DESTRUCTOR_INLINE // for specializing util::what namespace util { SPECIALIZE_UTIL_WHAT(HAC::parser::PRS::rule, "(prs-rule)") SPECIALIZE_UTIL_WHAT(HAC::parser::PRS::literal, "(prs-literal)") SPECIALIZE_UTIL_WHAT(HAC::parser::PRS::precharge, "(prs-precharge)") SPECIALIZE_UTIL_WHAT(HAC::parser::PRS::loop, "(prs-loop)") SPECIALIZE_UTIL_WHAT(HAC::parser::PRS::conditional, "(prs-conditional)") SPECIALIZE_UTIL_WHAT(HAC::parser::PRS::body, "(prs-body)") SPECIALIZE_UTIL_WHAT(HAC::parser::PRS::guarded_body, "(prs-guarded-body)") SPECIALIZE_UTIL_WHAT(HAC::parser::PRS::op_loop, "(prs-op-loop)") namespace memory { // explicit template instantiations using namespace HAC::parser::PRS; template class count_ptr<const body_item>; template class count_ptr<const guarded_body>; } // end namespace memory } // end namespace util namespace HAC { namespace parser { namespace PRS { using std::back_inserter; #include "util/using_ostream.hh" using entity::definition_base; using entity::process_definition; using entity::pint_scalar; using entity::pbool_expr; using entity::meta_range_expr; using entity::meta_loop_base; using entity::PRS::pull_base; using std::find; using std::find_if; using std::mem_fun_ref; //============================================================================= // class body_item method definitions #define CHECK_RULE_THROW THROW_EXIT #define GUARDED_PRS_THROW THROW_EXIT body_item::body_item() { } body_item::~body_item() { } //============================================================================= // class literal method definitions literal::literal(inst_ref_expr* r, const expr_attr_list* p) : ref(r), params(p), internal(false) { NEVER_NULL(ref); // params are optional } literal::literal(inst_ref_expr* r) : ref(r), params(NULL), internal(false) { NEVER_NULL(ref); // params are optional } literal::~literal() { } PARSER_WHAT_DEFAULT_IMPLEMENTATION(literal) ostream& literal::dump(ostream& o) const { FINISH_ME(Fang); return o; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** Destructively releases and exposes underlying identifier if it is a simple id_expr, else returns NULL (no error message). \return token_identifier if instance_reference is a single unqualified ID. */ excl_ptr<const token_identifier> literal::extract_identifier(void) { typedef excl_ptr<const token_identifier> return_type; excl_ptr<id_expr> idex = ref.is_a_xfer<id_expr>(); if (!idex) return return_type(NULL); excl_ptr<qualified_id> qid = idex->release_qualified_id(); NEVER_NULL(qid); if (qid->is_absolute()) return return_type(NULL); if (qid->size() > 1) return return_type(NULL); qualified_id_base::reference id(qid->front()); return_type ret(id.exclusive_release()); // transfer ownership NEVER_NULL(ret); return ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** Releases the parameters list to the caller. */ excl_ptr<const expr_attr_list> literal::extract_parameters(void) { return params; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** \param e is exclusivel owned (or freshly allocated). */ void literal::attach_parameters(const expr_attr_list* e) { params = excl_ptr<const expr_attr_list>(e); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - line_position literal::leftmost(void) const { return ref->leftmost(); } line_position literal::rightmost(void) const { if (params) return params->rightmost(); else return ref->rightmost(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - literal::attribute_type literal::check_literal_attribute(const generic_attribute& a, const context& c) { typedef attribute_type return_type; typedef expr_list::checked_meta_exprs_type vals_type; typedef vals_type::const_iterator const_iterator; typedef vals_type::value_type val_type; // attributes must be registered with the master registry list string key; if (a.key) { const entity::PRS::cflat_literal_attribute_registry_type::const_iterator f(entity::PRS::cflat_literal_attribute_registry.find(*a.key)); if (f == entity::PRS::cflat_literal_attribute_registry.end()) { // error handling: downgrade to warning? cerr << "Error: unrecognized PRS literal attribute \"" << *a.key << "\" at " << where(*a.key) << endl; return return_type(); } key = *a.key; } else { // implicit label= key when a plain string is provided key = "label"; } vals_type vals; if (a.values) { a.values->postorder_check_meta_exprs(vals, c); } const const_iterator i(vals.begin()), e(vals.end()); if (find(i, e, val_type(NULL)) != e) { // one of the param expressions failed checking // blank will signal error cerr << "Error in checking attribute value expressions in " << (a.values ? where(*a.values) : where(a)) << endl; return return_type(); } return_type ret(key); copy(i, e, back_inserter(ret)); return ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** TODO: use different lookup for internal nodes */ prs_literal_ptr_type literal::check_prs_literal(const context& c) const { STACKTRACE_VERBOSE; prs_literal_ptr_type ret; if (internal) { STACKTRACE_INDENT_PRINT("internal node setup" << endl); const never_ptr<const index_expr> ir(ref.is_a<const index_expr>()); never_ptr<const token_identifier> dr; // local-only count_ptr<const range_list> ind; if (ir) { if (!c.parse_opts.array_internal_nodes) { cerr << "Error: internal node arrays are unsupported " "in ACT mode. " << where(*this) << endl; return prs_literal_ptr_type(NULL); } const count_ptr<const inst_ref_expr>& b(ir->get_base()); dr = never_ptr<const token_identifier>( &*b.is_a<const token_identifier>()); NEVER_NULL(b && dr); ind = ir->get_indices(); } else { const never_ptr<const id_expr> b(ref.is_a<const id_expr>()); NEVER_NULL(b); dr = never_ptr<const token_identifier>(&*b->get_id()->front()); if (!dr) { cerr << "Unexpected prs-literal type: " << where(*ref) << endl; return prs_literal_ptr_type(NULL); } } const token_identifier& id(*dr); const never_ptr<const node_instance_placeholder> np(c.lookup_internal_node(id)); if (!np) { cerr << "Internal node `" << id << "\' not found." << endl; return prs_literal_ptr_type(NULL); } const count_ptr<entity::simple_node_meta_instance_reference> nref(new entity::simple_node_meta_instance_reference(np)); if (ind) { const range_list::checked_meta_indices_type checked_indices(ind->check_meta_indices(c)); if (!checked_indices) { cerr << "Error in internal node reference." << endl; return prs_literal_ptr_type(NULL); } nref->attach_indices(checked_indices); } if (params) { cerr << "Error: internal node references should not take parameters or attributes. " << where(*params) << endl; return prs_literal_ptr_type(NULL); } ret = prs_literal_ptr_type(new entity::PRS::literal( nref.as_a<const entity::simple_node_meta_instance_reference>())); NEVER_NULL(ret); } else { ret = ref->check_prs_literal(c); } if (ret && params) { // NOTE: parameters are not applicable to RHS or rules if (params->size() > 2) { cerr << "Error: rule literals can take a maximum of 2 " "(width, length) parameters. " << where(*params) << endl; return prs_literal_ptr_type(NULL); } typedef expr_list::checked_meta_exprs_type checked_exprs_type; typedef checked_exprs_type::const_iterator const_iterator; typedef checked_exprs_type::value_type value_type; checked_exprs_type temp; params->postorder_check_meta_exprs(temp, c); const const_iterator i(temp.begin()), e(temp.end()); if (find(i, e, value_type(NULL)) != e) { cerr << "Error checking literal parameters in " << where(*params) << endl; return prs_literal_ptr_type(NULL); } NEVER_NULL(ret); copy(i, e, back_inserter(ret->get_params())); if (params->attrs) { // handle attributes entity::generic_attribute_list_type& atts(ret->get_attributes()); params->attrs->check_list(atts, &check_literal_attribute, c); if (find(atts.begin(), atts.end(), false) != atts.end()) { cerr << "ERROR in literal attribute list. " << where(*params->attrs) << endl; THROW_EXIT; } } } return ret; } // end literal::check_prs_literal //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** Called to check a literal on the RHS of a rule. Special case needed when literal is marked as internal node, in which case this is a *declaration* of an internal node. Signal to caller that this is internal (flag the created IR literal). */ prs_literal_ptr_type literal::check_prs_rhs(context& c) const { STACKTRACE_VERBOSE; if (internal) { STACKTRACE_INDENT_PRINT("internal node setup" << endl); // inject an implicit internal node declaration const never_ptr<const index_expr> ir(ref.is_a<const index_expr>()); const never_ptr<const id_expr> dr(ref.is_a<const id_expr>()); never_ptr<const node_instance_placeholder> nd; if (ir) { if (!c.parse_opts.array_internal_nodes) { cerr << "Error: internal node arrays are unsupported " "in ACT mode. " << where(*this) << endl; return prs_literal_ptr_type(NULL); } // extract base and index dimensions const count_ptr<const inst_ref_expr>& b(ir->get_base()); const count_ptr<const token_identifier> bd(b.is_a<const token_identifier>()); NEVER_NULL(b && bd); nd = c.add_internal_node(*bd, ir->implicit_dimensions()); // only care about dimensions, not indices } else if (dr) { // is a scalar nd = c.add_internal_node(*dr->get_id()->front(), 0); } else { cerr << "Unexpected prs-literal type: " << where(*ref) << endl; return prs_literal_ptr_type(NULL); } if (!nd) { cerr << "Error implicitly declaring internal node. " << where(*ref) << endl; return prs_literal_ptr_type(NULL); } // now return to normal lookup } return check_prs_literal(c); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** This really should never be called. Meta-parameter references should never be adorned with other parameters! */ inst_ref_expr::meta_return_type literal::check_meta_reference(const context& c) const { // return ref->check_meta_reference(c); return meta_return_type(NULL); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** This really should never be called. Postpone parameter checks until later. */ inst_ref_expr::nonmeta_return_type literal::check_nonmeta_reference(const context& c) const { // return ref->check_nonmeta_reference(c); return nonmeta_return_type(NULL); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int literal::expand_const_reference(const count_ptr<const inst_ref_expr>&, reference_array_type&) const { ICE_NEVER_CALL(cerr); return 1; } //============================================================================= // class precharge method definitions precharge::precharge(const node_position* d, const expr* e) : dir(d), pchg_expr(e) { NEVER_NULL(d); NEVER_NULL(pchg_expr); } precharge::~precharge() { } PARSER_WHAT_DEFAULT_IMPLEMENTATION(precharge) line_position precharge::leftmost(void) const { return dir->leftmost(); } line_position precharge::rightmost(void) const { return pchg_expr->rightmost(); } entity::PRS::precharge_expr precharge::check_prs_expr(context& c) const { if (pchg_expr) { const prs_expr_return_type e(pchg_expr->check_prs_expr(c)); if (e) { return entity::PRS::precharge_expr(e, dir->text[0] == '+'); } } return entity::PRS::precharge_expr(); // default } //============================================================================= // class rule method definitions /** \param atts the attribute list is optional. */ CONSTRUCTOR_INLINE rule::rule(const generic_attribute_list* atts, const expr* g, const char_punctuation_type* a, literal* rhs, const char_punctuation_type* d) : body_item(), attribs(atts), guard(g), arrow(a), r(rhs), dir(d) { NEVER_NULL(guard); NEVER_NULL(arrow); NEVER_NULL(r); NEVER_NULL(dir); } DESTRUCTOR_INLINE rule::~rule() { } PARSER_WHAT_DEFAULT_IMPLEMENTATION(rule) line_position rule::leftmost(void) const { if (attribs) return attribs->leftmost(); else return guard->leftmost(); } line_position rule::rightmost(void) const { return dir->rightmost(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** Type-checks and constructs a production rule. \return a newly constructed, type-checked production rule, to be added to a definition. TODO: better error handling, instead of throwing exception... */ body_item::return_type rule::check_rule(context& c) const { STACKTRACE_VERBOSE; prs_expr_return_type g(guard->check_prs_expr(c)); if (!g) { cerr << "ERROR in production rule guard at " << where(*guard) << "." << endl; THROW_EXIT; } // g->check(); // paranoia prs_literal_ptr_type o(r->check_prs_rhs(c)); if (!o) { cerr << "ERROR in the output node reference at " << where(*r) << "." << endl; THROW_EXIT; } char arrow_type = pull_base::ARROW_NORMAL; switch (arrow->text[0]) { case '=': arrow_type = pull_base::ARROW_COMPLEMENT; break; case '#': arrow_type = pull_base::ARROW_FLIP; break; default: {} } if (arrow_type && o->is_internal()) { cerr << "ERROR: internal nodes may only be defined with -> . " << where(*this) << endl; THROW_EXIT; } excl_ptr<pull_base> ret((dir->text[0] == '+') ? AS_A(pull_base*, new entity::PRS::pull_up(g, *o, arrow_type)) : AS_A(pull_base*, new entity::PRS::pull_dn(g, *o, arrow_type))); NEVER_NULL(ret); if (attribs) { entity::PRS::rule_attribute_list_type& atts(ret->get_attribute_list()); attribs->check_list(atts, &check_prs_attribute, c); if (find(atts.begin(), atts.end(), false) != atts.end()) { cerr << "ERROR in attributes list before rule." << endl; THROW_EXIT; } } c.get_current_prs_body().append_rule(ret); // FIXME: missing return? shouldn't compiler warn? } //============================================================================= // class loop method definitions loop::loop(const char_punctuation_type* l, const token_identifier* id, const range* b, const rule_list* rl, const char_punctuation_type* r) : body_item(), lp(l), index(id), bounds(b), rules(rl), rp(r) { NEVER_NULL(index); NEVER_NULL(bounds); NEVER_NULL(rules); } loop::~loop() { } PARSER_WHAT_DEFAULT_IMPLEMENTATION(loop) line_position loop::leftmost(void) const { if (lp) return lp->leftmost(); else return index->leftmost(); } line_position loop::rightmost(void) const { if (rp) return rp->rightmost(); else return rules->rightmost(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** TODO: have PRS::rule return a entity::PRS::rule. */ body_item::return_type loop::check_rule(context& c) const { STACKTRACE_VERBOSE; // declare induction variable using token_identifier // check for shadowing by looking up // extend/modify the parse context with token_identifier on stack // type-check the range expression // type-check the inside expression with modified context const range::meta_return_type rng(bounds->check_meta_index(c)); if (!rng) { cerr << "Error in loop range at " << where(*bounds) << endl; // bounds->dump(cerr) << return return_type(NULL); } // convert implicit range to explicit range, if necessary entity::PRS::expr_loop_base::range_ptr_type loop_range(meta_range_expr::make_explicit_range(rng)); NEVER_NULL(loop_range); // create loop index variable and push onto context stack const context::loop_var_frame _lvf(c, *index); const meta_loop_base::ind_var_ptr_type& loop_ind(_lvf.var); if (!loop_ind) { // then push didn't succeed, no need to pop cerr << "Error registering loop variable: " << *index << " at " << where(*index) << endl; return return_type(NULL); } excl_ptr<entity::PRS::rule_loop> ret(new entity::PRS::rule_loop(loop_ind, loop_range)); NEVER_NULL(ret); // copied from body::check_rule // const never_ptr<definition_base> d(c.get_current_open_definition()); never_ptr<entity::PRS::rule_loop> retc(ret); c.get_current_prs_body().append_rule(ret); try { const context::prs_body_frame prlf(c, retc); rules->check_list_void(&body_item::check_rule, c); } catch (...) { cerr << "ERROR: at least one error in PRS rule-loop. " << where(*rules) << endl; throw; // re-throw } if (retc->empty()) { c.get_current_prs_body().pop_back(); } } // end method loop::check_rule //============================================================================= // class guarded_body method definitions guarded_body::guarded_body(const expr* g, const char_punctuation_type* a, const rule_list* r) : guard(g), arrow(a), rules(r) { // guard may be NULL (else-clause) NEVER_NULL(arrow); NEVER_NULL(rules); } guarded_body::~guarded_body() { } PARSER_WHAT_DEFAULT_IMPLEMENTATION(guarded_body) line_position guarded_body::leftmost(void) const { if (guard) return guard->leftmost(); else return arrow->leftmost(); } line_position guarded_body::rightmost(void) const { return rules->rightmost(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - guarded_body::return_type guarded_body::check_clause(context& c) const { STACKTRACE_VERBOSE; expr::meta_return_type _g(NULL); entity::meta_conditional_base::guard_ptr_type bg(NULL); if (guard && !guard.is_a<const token_else>()) { _g = guard->check_meta_expr(c); if (!_g) { cerr << "Error checking guard expression of " "conditional PRS. " << where(*guard) << endl; GUARDED_PRS_THROW; } else { bg = _g.is_a<const pbool_expr>(); if (!bg) { cerr << "Error: guard expression is not boolean. " << where(*guard) << endl; GUARDED_PRS_THROW; } } } // see also guarded_instance_management::check_build() const never_ptr<entity::PRS::rule_conditional> rs(IS_A(entity::PRS::rule_conditional*, &*c.get_current_prs_body().back())); NEVER_NULL(rs); rs->append_guarded_clause(bg); const context::prs_body_frame _pbf(c, never_ptr<entity::PRS::rule_set_base>(&rs->get_last_clause())); STACKTRACE_INDENT_PRINT("current rule set: " << &rs->get_last_clause() << endl); // code below mostly ripped from loop::check_rule() try { rules->check_list_void(&body_item::check_rule, c); } catch (...) { cerr << "ERROR: at least one error in conditional PRS rules. " << where(*rules) << endl; } } // end guarded_body::check_clause //============================================================================= // class conditional method definitions conditional::conditional(const guarded_prs_list* p) : gp(p) { NEVER_NULL(gp); } conditional::~conditional() { } PARSER_WHAT_DEFAULT_IMPLEMENTATION(conditional) line_position conditional::leftmost(void) const { return gp->leftmost(); } line_position conditional::rightmost(void) const { return gp->leftmost(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** TODO: generalize to multiple else-if clauses. */ body_item::return_type conditional::check_rule(context& c) const { STACKTRACE_VERBOSE; // see also conditional_instantiation::check_build() excl_ptr<entity::PRS::rule_conditional> rs(new entity::PRS::rule_conditional()); const never_ptr<const entity::PRS::rule_conditional> crs(rs); c.get_current_prs_body().append_rule(rs); // xfer ownership MUST_BE_NULL(rs); gp->check_list_void(&guarded_body::check_clause, c); if (crs->empty()) { c.get_current_prs_body().pop_back(); } } // end conditional::check_rule //============================================================================= // class body method definitions CONSTRUCTOR_INLINE body::body(const generic_keyword_type* t, const inst_ref_expr_list* s, const rule_list* r) : language_body(t), supplies(s), rules(r) { if (r) NEVER_NULL(rules); } DESTRUCTOR_INLINE body::~body() { } PARSER_WHAT_DEFAULT_IMPLEMENTATION(body) line_position body::leftmost(void) const { return language_body::leftmost(); } line_position body::rightmost(void) const { return rules->rightmost(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** \return false on error. */ bool body::__check_rules(context& c) const { if (rules) { if (supplies) { inst_ref_expr_list::checked_bool_refs_type temp; if (supplies->postorder_check_bool_refs_optional(temp, c)) { cerr << "Error in PRS supply overrides. " << where(*supplies) << endl; return false; } const size_t s = temp.size(); if (s > 4 || s < 1) { cerr << "Error: PRS supply/substrate overrides are of the form:\n" "\t<Vdd [,GND] [| BVdd [,BGND]]>\n\terror at: " << where(*supplies) << endl; return false; } entity::PRS::rule_set& r(IS_A(entity::PRS::rule_set&, c.get_current_prs_body())); // throw bad_case if cast fails if (temp[0]) r.Vdd = temp[0]->get_bool_var(); if (s > 1 && temp[1]) r.GND = temp[1]->get_bool_var(); if (s > 2 && temp[2]) r.Vdd_substrate = temp[2]->get_bool_var(); // else r.Vdd_substrate = r.Vdd; if (s > 3 && temp[3]) r.GND_substrate = temp[3]->get_bool_var(); // else r.GND_substrate = r.GND; } try { rules->check_list_void(&body_item::check_rule, c); } catch (...) { return false; } } return true; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** NOTE: remember to update return type with ROOT_CHECK_PROTO. Currently, exits upon error. Added support for prs inside conditionals and loops from the instance management scope. \pre context has already set the current_prs_body. */ never_ptr<const object> body::check_build(context& c) const { STACKTRACE_VERBOSE; if (rules) { if (c.reject_namespace_lang_body()) { cerr << "Error: top-level PRS is only supported " "in the global namespace." << endl; cerr << "\tgot: prs { ... } " << where(*this) << endl; THROW_EXIT; } // check context's current open definition const never_ptr<definition_base> d(c.get_current_open_definition()); const never_ptr<process_definition> pd(d.is_a<process_definition>()); // if !pd, then prs is in a top-level scope (outside definition) // need to open a separate body because we only want supply overrides // to apply to its own group of nodes // copied from body::check_rule typedef entity::PRS::rule_set rule_set; excl_ptr<rule_set> ret(new rule_set()); NEVER_NULL(ret); const never_ptr<rule_set> retc(ret); entity::PRS::rule_set_base& rb(c.get_current_prs_body()); rb.append_rule(ret); const context::prs_body_frame prf(c, retc); if (!__check_rules(c)) { cerr << "ERROR: at least one error in PRS body." << endl; THROW_EXIT; } if (retc->empty()) { rb.pop_back(); } } // else empty, no PRS to add return never_ptr<const object>(NULL); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** Treat nested body of rules as a continuation of the list of rules. TODO: factor out common checking loop with check_build, above. */ body_item::return_type body::check_rule(context& c) const { if (!__check_rules(c)) { cerr << "ERROR: at least one error in PRS rule-nest. " << where(*rules) << endl; CHECK_RULE_THROW; } } //============================================================================= // class subcircuit method definition subcircuit::subcircuit(const generic_keyword_type* k, const expr_list* p, const rule_list* r) : body(k, NULL, // no subcircuit supply overriding, use parent's r), params(p) { // params may be optional } subcircuit::~subcircuit() { } PARSER_WHAT_DEFAULT_IMPLEMENTATION(subcircuit) /** For now make transparent. */ never_ptr<const object> subcircuit::check_build(context& c) const { return body::check_build(c); } body_item::return_type subcircuit::check_rule(context& c) const { STACKTRACE_VERBOSE; string name; if (params) { static const char err_msg[] = "ERROR: expecting at most one string-literal for subcircuit name. "; bool err = true; expr_list::checked_meta_exprs_type e; params->postorder_check_meta_exprs(e, c); if (e.size() == 1) { // e.front()->what(cout << "s = ") << endl; const count_ptr<const entity::pstring_expr> s(e.front().is_a<const entity::pstring_expr>()); if (s) { name = s->static_constant_value(); err = false; } } if (err) { cerr << err_msg << where(*params) << endl; THROW_EXIT; } } excl_ptr<entity::PRS::subcircuit> ret(new entity::PRS::subcircuit(name)); NEVER_NULL(ret); // copied from body::check_rule // const never_ptr<definition_base> d(c.get_current_open_definition()); const never_ptr<entity::PRS::subcircuit> retc(ret); entity::PRS::rule_set_base& rb(c.get_current_prs_body()); rb.append_rule(ret); try { const context::prs_body_frame prlf(c, retc); rules->check_list_void(&body_item::check_rule, c); #if 0 if (!__check_rules(c)) { cerr << "ERROR: at least one error in subckt rule-nest. " << where(*rules) << endl; CHECK_RULE_THROW; } #endif } catch (...) { cerr << "ERROR: at least one error in PRS subcircuit. " << where(*rules) << endl; throw; // re-throw } if (retc->empty()) { rb.pop_back(); } } //============================================================================= // class op_loop method definitions op_loop::op_loop(const char_punctuation_type* l, const char_punctuation_type* o, const token_identifier* id, const range* b, const expr* e, const char_punctuation_type* r) : expr(), lp(l), op(o), index(id), bounds(b), ex(e), rp(r) { NEVER_NULL(op); NEVER_NULL(index); NEVER_NULL(bounds); NEVER_NULL(ex); } op_loop::~op_loop() { } ostream& op_loop::what(ostream& o) const { o << '(' << util::what<op_loop>::name() << ' '; return op->what(o) << ")"; } ostream& op_loop::dump(ostream& o) const { FINISH_ME(Fang); return o; } line_position op_loop::leftmost(void) const { if (lp) return lp->leftmost(); else return op->leftmost(); } line_position op_loop::rightmost(void) const { if (rp) return rp->rightmost(); else return ex->rightmost(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** TODO: FINISH ME Is this even needed outside of the PRS context? */ expr::meta_return_type op_loop::check_meta_expr(const context& c) const { FINISH_ME(Fang); return expr::meta_return_type(NULL); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** TODO: FINISH ME Is this even needed outside of the PRS context? */ nonmeta_expr_return_type op_loop::check_nonmeta_expr(const context& c) const { FINISH_ME(Fang); return nonmeta_expr_return_type(NULL); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - prs_expr_return_type op_loop::check_prs_expr(context& c) const { // declare induction variable using token_identifier // check for shadowing by looking up // extend/modify the parse context with token_identifier on stack // type-check the range expression // type-check the inside expression with modified context const range::meta_return_type rng(bounds->check_meta_index(c)); if (!rng) { cerr << "Error in loop range at " << where(*bounds) << endl; // bounds->dump(cerr) << return prs_expr_return_type(NULL); } // convert implicit range to explicit range, if necessary const entity::PRS::expr_loop_base::range_ptr_type loop_range(meta_range_expr::make_explicit_range(rng)); NEVER_NULL(loop_range); // create loop index variable and push onto context stack const context::loop_var_frame _lvf(c, *index); const meta_loop_base::ind_var_ptr_type& loop_ind(_lvf.var); if (!loop_ind) { // then push didn't succeed, no need to pop cerr << "Error registering loop variable: " << *index << " at " << where(*index) << endl; return prs_expr_return_type(NULL); } const prs_expr_return_type body_expr(ex->check_prs_expr(c)); if (!body_expr) { cerr << "Error in expr-loop body: at " << where(*ex) << endl; // ex->dump(cerr) << return prs_expr_return_type(NULL); } // else everything passes return (op->text[0] == '&') ? prs_expr_return_type(new entity::PRS::and_expr_loop( loop_ind, loop_range, body_expr)) : prs_expr_return_type(new entity::PRS::or_expr_loop( loop_ind, loop_range, body_expr)); } //============================================================================= // class macro method definitions macro::macro(const generic_attribute_list* a, literal* l, const inst_ref_expr_list* r) : attribs(a), name(), params(), args(r) { const excl_ptr<literal> lit(l); // will self-destruct at end of ctor name = lit->extract_identifier(); params = lit->extract_parameters(); // punt checking until later } macro::~macro() { } PARSER_WHAT_DEFAULT_IMPLEMENTATION(macro) line_position macro::leftmost(void) const { // there could be an error extracting the name if (attribs) return attribs->leftmost(); else if (name) return name->leftmost(); else if (params) return params->leftmost(); else return args->leftmost(); } line_position macro::rightmost(void) const { return args->rightmost(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** TODO: process params. */ body_item::return_type macro::check_rule(context& c) const { if (!name) { cerr << "Error parsing macro name before " << where(*args) << endl; cerr << "Expected: prs_macro : ID . [ \'<\' shift_exprs \'>\' ] \'(\' inst_ref_exprs \')\'" << endl; CHECK_RULE_THROW; } const entity::PRS::cflat_macro_registry_type::const_iterator f(entity::PRS::cflat_macro_registry.find(*name)); if (f == entity::PRS::cflat_macro_registry.end()) { cerr << "Error: unrecognized PRS macro \"" << *name << "\" at " << where(*name) << endl; CHECK_RULE_THROW; } const entity::PRS::cflat_macro_definition_entry& mde(f->second); excl_ptr<entity::PRS::macro> ret(new entity::PRS::macro(*name)); if (params) { if (!mde.check_num_params(params->size()).good) { // already have error message cerr << "\tat " << where(*params) << endl; CHECK_RULE_THROW; } typedef expr_list::checked_meta_exprs_type checked_exprs_type; typedef checked_exprs_type::const_iterator const_iterator; typedef checked_exprs_type::value_type value_type; checked_exprs_type temp; params->postorder_check_meta_exprs(temp, c); const const_iterator i(temp.begin()), e(temp.end()); if (find(i, e, value_type(NULL)) != e) { cerr << "Error checking macro parameters in " << where(*args) << endl; CHECK_RULE_THROW; } // INVARIANT(temp.size()); // params may be empty NEVER_NULL(ret); copy(i, e, back_inserter(ret->get_params())); if (params->attrs) { // handle attributes, treat as literal attributes for now... entity::generic_attribute_list_type& atts(ret->get_attributes()); params->attrs->check_list(atts, &literal::check_literal_attribute, AS_A(const context&, c)); if (find(atts.begin(), atts.end(), false) != atts.end()) { cerr << "ERROR in macro attribute list. " << where(*params->attrs) << endl; THROW_EXIT; } } } else if (!mde.check_num_params(0).good) { // no params given where required and already have error message cerr << "\tat " << where(*this) << endl; CHECK_RULE_THROW; } { typedef inst_ref_expr_list::checked_bool_groups_type checked_bools_type; NEVER_NULL(args); if (!mde.check_num_nodes(args->size()).good) { // already have error message cerr << "\tat " << where(*args) << endl; CHECK_RULE_THROW; } typedef checked_bools_type::const_iterator const_iterator; typedef checked_bools_type::value_type value_type; checked_bools_type temp; INVARIANT(args->size()); args->postorder_check_grouped_bool_refs(temp, c); const const_iterator i(temp.begin()), e(temp.end()); if (find_if(i, e, mem_fun_ref(&value_type::empty)) != e) { cerr << "Error checking macro arguments in " << where(*args) << endl; CHECK_RULE_THROW; } INVARIANT(temp.size()); NEVER_NULL(ret); copy(i, e, back_inserter(ret->get_nodes())); } if (attribs) { cerr << "WARNING: attributes on PRS macros are tentatively ignored. " << where(*attribs) << endl; ++c.warning_count; // FINISH_ME(Fang); } c.get_current_prs_body().append_rule(ret); } // end macro::check_rule //============================================================================= // class attribute method definitions rule::attribute_type rule::check_prs_attribute(const generic_attribute& a, context& c) { typedef attribute_type return_type; typedef expr_list::checked_meta_exprs_type vals_type; typedef vals_type::const_iterator const_iterator; typedef vals_type::value_type val_type; // all macros must be registered with the master registry list (cflat) const entity::PRS::cflat_rule_attribute_registry_type::const_iterator f(entity::PRS::cflat_rule_attribute_registry.find(*a.key)); if (f == entity::PRS::cflat_rule_attribute_registry.end()) { cerr << "Error: unrecognized PRS rule attribute \"" << *a.key << "\" at " << where(*a.key) << endl; return return_type(); } vals_type vals; if (a.values) { a.values->postorder_check_meta_exprs(vals, c); } const const_iterator i(vals.begin()), e(vals.end()); if (find(i, e, val_type(NULL)) != e) { // one of the param expressions failed checking // blank will signal error cerr << "Error in checking attribute value expressions in " << (a.values ? where(*a.values) : where(a)) << endl; return return_type(); } return_type ret(*a.key); copy(i, e, back_inserter(ret)); return ret; } //============================================================================= } // end namespace PRS //============================================================================= // EXPLICIT TEMPLATE INSTANTIATIONS -- entire classes // template class node_list<const body_item>; // PRS::rule_list #if 1 // This is temporary, until node_list::check_build is overhauled. template node_list<const PRS::body_item>::node_list(); template node_list<const PRS::body_item>::node_list(const PRS::body_item*); template node_list<const PRS::body_item>::~node_list(); template ostream& node_list<const PRS::body_item>::what(ostream&) const; template line_position node_list<const PRS::body_item>::leftmost(void) const; template line_position node_list<const PRS::body_item>::rightmost(void) const; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // template // node_list<const PRS::guarded_body>::node_list(); template node_list<const PRS::guarded_body>::node_list(const PRS::guarded_body*); template node_list<const PRS::guarded_body>::~node_list(); template ostream& node_list<const PRS::guarded_body>::what(ostream&) const; template line_position node_list<const PRS::guarded_body>::leftmost(void) const; template line_position node_list<const PRS::guarded_body>::rightmost(void) const; #endif //============================================================================= } // end namespace parser } // end namespace HAC #undef CONSTRUCTOR_INLINE #undef DESTRUCTOR_INLINE #endif // __HAC_AST_PRS_CC__
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r14 push %rbx push %rcx push %rdi push %rsi lea addresses_WC_ht+0x1819e, %rsi nop nop nop add $55048, %rbx mov $0x6162636465666768, %r13 movq %r13, (%rsi) and $44055, %r11 lea addresses_A_ht+0x1be2a, %r13 nop nop nop nop add $41642, %rdi mov $0x6162636465666768, %r14 movq %r14, %xmm4 movups %xmm4, (%r13) nop nop nop nop cmp %r11, %r11 lea addresses_UC_ht+0x2f4e, %rsi lea addresses_normal_ht+0xbb3e, %rdi nop add %rbx, %rbx mov $10, %rcx rep movsb nop nop nop nop nop add %r13, %r13 lea addresses_WT_ht+0x52e, %rsi clflush (%rsi) nop nop sub $17998, %rdi mov (%rsi), %r14 nop nop nop nop nop cmp %r11, %r11 lea addresses_WC_ht+0x1e94e, %r13 nop cmp %rsi, %rsi mov (%r13), %rdi and %r14, %r14 pop %rsi pop %rdi pop %rcx pop %rbx pop %r14 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r14 push %r8 push %rbp push %rsi // Faulty Load lea addresses_normal+0x794e, %r12 nop and $49932, %rsi mov (%r12), %r8d lea oracles, %rbp and $0xff, %r8 shlq $12, %r8 mov (%rbp,%r8,1), %r8 pop %rsi pop %rbp pop %r8 pop %r14 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_normal', 'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 4}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 2}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}, 'dst': {'same': True, 'congruent': 4, 'type': 'addresses_normal_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 3}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 11}} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
MOV A,#0XA0 MOVC A, @A+PC ;0xAA MOV A,#0xFF MOVC A, @A+PC ;0x0F LJMP 0xAAAA CSEG AT 0xA3 DB 0xAA CSEG AT 0x105 DB 0x0F CSEG AT 0xAAAA;0xF0 MOV A,#0x02 MOVC A,@A+PC NOP NOP DB 0xF0